views:

3318

answers:

5

Hi,

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

Thanks..

A: 

There still is a distanceFrom function on the GLatLng object, but the function parameters have slightly changed between v2 and v3.

tomlog
Are you sure this is the case? The documentation [does not list it](http://code.google.com/apis/maps/documentation/v3/reference.html#LatLng).
mikl
You're actually quite right there. The v3 documentation does indeed not mention the distanceFrom function, and the link in my reply was indeed pointing to v2.
tomlog
A: 

take a look at:

http://code.google.com/apis/maps/documentation/reference.html#GLatLng.GLatLng

e.g:

function initialize() {
      if (GBrowserIsCompatible()) {
          map = new GMap2(document.getElementById("map_canvas"));
          map.setCenter(new GLatLng(52.6345701, -1.1294433), 13);
          map.addControl(new GLargeMapControl());          
          map.addControl(new GMapTypeControl());
          geocoder = new GClientGeocoder();

          // NR14 7PZ
          var loc1 = new GLatLng(52.5773139, 1.3712427);
          // NR32 1TB
          var loc2 = new GLatLng(52.4788314, 1.7577444);          
          alert(loc2.distanceFrom(loc1) / 1000);
      }
    }
Richard
Am i correct distance form is not suported in V3 because i am getting error on it...
Waheed
Your example uses GMap2 – the questioner specified GMap3.
mikl
Sorry my mistake
Richard
+14  A: 

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

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);
}
Mike Williams
+2  A: 

You can get good accuracy at the cost of increased processing time with the Vincenty algorithm, implemented in Javascript.

Andrew
A: 

I have a different dilemma. How would you calculate the second point, giving the distance in km? In other words, having the radius of a circle, how would you figure out the LatLng of the second point in S W and N E directions?

Luis Merino
I found the answer to my problem. I anybody is interested refer to: movable-type.co.uk/scripts/latlong.html -> "Destination point given distance and bearing from start point"
Luis Merino