如何使用谷歌地图获取距离?

时间:2011-08-01 07:24:08

标签: php cakephp curl

如果你试图找到距离:

Kalyani Nagar, Wadgaon Sheri, Pune, Maharashtra, India
Karve Nagar, Hingne Budrukh, Pune, Maharashtra, India

使用此网址我们获得的距离为3.4953372691389英里

http://www.sudhirhub.com/2010/05/find-distance-between-two-cities-using.html

你在maps.google.com获得

N Main Road 8.8 mi

这个距离是公路所以距离太大。

是否有任何API /任何CURL请求会给我与maps.google.com相同的距离?

2 个答案:

答案 0 :(得分:0)

试试这个

rad = function(x) {return x*Math.PI/180;}

distHaversine = function(p1, p2) {
  var R = 6371; // earth's mean radius in km
  var dLat  = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());

  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) *          Math.sin(dLong/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;

  return d.toFixed(3);
 }

或使用

请确保将其包含在您的头部。

 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>

,电话会是

google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);

Refrence

答案 1 :(得分:-1)

查看example here。您需要做的就是请求该URL并通过json_decode()运行结果。类似的东西:

$result = file_get_contents('http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false');
$result = json_decode($results);
$distance = $result->routes->legs->distance['text'];
echo $distance // Outputs: "583 mi"