Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate distance between two points in google maps V3

How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom function inV2.)

Thanks..

like image 442
Waheed Avatar asked Oct 01 '09 08:10

Waheed


People also ask

Can Google Maps API calculate distance between two points?

What can you do with the Distance Matrix API? The API returns information based on the recommended route between start and end points. You can request distance data for different travel modes, request distance data in different units such kilometers or miles, and estimate travel time in traffic.

How do you find the distance between two points in 3d?

To find the distance between two points, take the coordinates of two points such as (x1, y1) and (x2, y2) Use the distance formula (i.e) square root of (x2 – x1)2 + (y2 – y1) For this formula, calculate the horizontal and vertical distance between two points.


2 Answers

If you want to calculate it yourself, then you can use the Haversine formula:

var rad = function(x) {   return x * Math.PI / 180; };  var getDistance = function(p1, p2) {   var R = 6378137; // Earth’s mean radius in meter   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; // returns the distance in meter }; 
like image 152
Mike Williams Avatar answered Oct 02 '22 08:10

Mike Williams


There actually seems to be a method in GMap3. It's a static method of the google.maps.geometry.spherical namespace.

It takes as arguments two LatLng objects and will utilize a default Earth radius of 6378137 meters, although the default radius can be overridden with a custom value if necessary.

Make sure you include:

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

in your head section.

The call will be:

google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB); 
like image 22
Emil Badh Avatar answered Oct 02 '22 08:10

Emil Badh