Hi,
How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom
function inV2.)
Thanks..
Hi,
How do you calculate the distance between two markers in Google maps V3? (Similar to the distanceFrom
function inV2.)
Thanks..
There still is a distanceFrom function on the GLatLng object, but the function parameters have slightly changed between v2 and v3.
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);
}
}
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);
}
You can get good accuracy at the cost of increased processing time with the Vincenty algorithm, implemented in Javascript.
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?