SoFunction
Updated on 2025-03-02

Golang and PHP implement method to calculate the distance between two latitudes and longitudes

This article describes the method of calculating the distance between two latitudes and longitudes and longitudes and longitudes. Share it for your reference, as follows:

golang version:

Copy the codeThe code is as follows:
package main
import (
    "fmt"
    "math"
)
func main() {
    lat1 := 29.490295
    lng1 := 106.486654
    lat2 := 29.615467
    lng2 := 106.581515
    (EarthDistance(lat1, lng1, lat2, lng2))
}
// The return value is meters
func EarthDistance(lat1, lng1, lat2, lng2 float64) float64 {
    radius := float64(6371000) // 6378137
    rad := /180.0
    lat1 = lat1 * rad
    lng1 = lng1 * rad
    lat2 = lat2 * rad
    lng2 = lng2 * rad
    theta := lng2 - lng1
    dist := ((lat1) * (lat2) + (lat1) * (lat2) * (theta))
    return dist * radius
}

php version:

<?php
// The return value is metersfunction pc_sphere_distance($lat1, $lon1, $lat2, $lon2, $radius = 6371000) {
  $rad = doubleval(M_PI/180.0);
  $lat1 = doubleval($lat1) * $rad;
  $lon1 = doubleval($lon1) * $rad;
  $lat2 = doubleval($lat2) * $rad;
  $lon2 = doubleval($lon2) * $rad;
  $theta = $lon2 - $lon1;
  $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));
  return $dist * $radius * 1000;
}
$lat1 = 29.490295;
$lon1 = 106.486654;
$lat2 = 29.615467;
$lon2 = 106.581515;
echo pc_sphere_distance($lat1, $lon1, $lat2, $lon2);

I hope this article will be helpful to everyone's Go language programming.