Home > Backend Development > PHP Tutorial > Golang and PHP implement the method of calculating the distance between two longitudes and latitudes

Golang and PHP implement the method of calculating the distance between two longitudes and latitudes

WBOY
Release: 2016-07-27 16:56:26
Original
1110 people have browsed it

The example in this article describes the method of calculating the distance between two longitudes and latitudes using golang and php. Share it with everyone for your reference, the details are as follows:

golang version:

Copy code The code is as follows:

package main
import (
"fmt"
"math"
)
func main() {
lat1 := 29.490295
lng1 := 106.486654
lat2 := 29.615467
lng2 := 106.581515
fmt.Println(EarthDistance(lat1, lng1, lat2, lng2))
}
//The unit of the return value is meters
func EarthDistance( lat1, lng1, lat2, lng2 float64) float64 {
radius := float64(6371000) // 6378137
rad := math.Pi/180.0
lat1 = lat1 * rad
lng1 = lng1 * rad
lat2 = lat2 * rad
lng2 = lng2 * rad
theta := lng2 - lng1
dist := math.Acos(math.Sin(lat1) * math.Sin(lat2) + math.Cos(lat1) * math.Cos(lat2) * math. Cos(theta))
Return dist * radius
}

php version:

<?php
// 返回值的单位为米
function 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);

Copy after login

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

The above introduces the method of calculating the distance between two longitudes and latitudes in golang and PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template