calculate distance between two locations in google maps


How do you calculate the distance between two locations(points or lat/lang) in Google Maps using javascript or jquery?
thank you

Asked by:- jaiprakash
1
: 231 At:- 6/6/2017 11:13:26 AM
javascript jquery google-maps






1 Answers
profileImage Answered by:- vikas_jk

Ok so you can calculate it using built-in google maps function or you can create it of your own

Solution 1(built-in)

There is the computeDistanceBetween(lat,lng) in the new V3 Geometry Library

code for it would be

var latitude1 = 40;
var longitude1 = 0.36;
var latitude2 = 41;
var longitude2 = 3.68;

var TotalDistanceInMeters= google.maps.geometry.spherical.computeDistanceBetween
(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));

Solution 2 (Create your own function):

 

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

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s 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; // return distance in meter
};

//Call it like
var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);

getDistance(loc1,loc2)

That's it, but I think solution 1 is better.

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

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s 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; // return distance in meter
};

//Do not use this
//var loc1 = new GLatLng(52.5773139, 1.3712427);
//var loc2 = new GLatLng(52.4788314, 1.7577444);
//use this instead
var Location1 = new google.maps.LatLng(lat1, lng1);
var location2 = new google.maps.LatLng(lat2, lng2);

getDistance(loc1,loc2)
1
At:- 6/6/2017 12:41:43 PM Updated at:- 6/7/2017 7:34:38 AM
great answer, i will implement it, and will let you know about the outcome, thank you 0
By : jaiprakash - at :- 6/6/2017 12:47:58 PM
I am getting an issue while using solution 2, new GLatLng(52.5773139, 1.3712427) is not defined. how to resolve it? 1
By : jaiprakash - at :- 6/7/2017 7:26:10 AM
Ok, i have updated my answer, it should work now 0
By : vikas_jk - at :- 6/7/2017 7:34:56 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use