view raw
Anbazhagan Anbazhagan - 7 months ago 49
Javascript Question

How can I get distance from given path value in Google Maps JavaScript API?

I have integrated Google Maps JavaScript API in my application. I need to calculate travelled distance by given path.

Path is like,

var path = [
{lat: 36.579, lng: -118.292},
{lat: 36.606, lng: -118.0638},
{lat: 36.433, lng: -117.951},
{lat: 36.588, lng: -116.943},
{lat: 36.34, lng: -117.468},
{lat: 36.24, lng: -116.832}];

Using above value need to calculate distance. Give me your valuable idea.


To use the Google Maps Javascript API v3 spherical geometry distance methods, the "points" need to be google.maps.LatLng objects, not google.maps.LatLngLiteral objects.

There are at least four options:

  1. convert your array of google.maps.LatLngLiterals to google.maps.LatLng objects.
var path = [
      new google.maps.LatLng(36.579, -118.292),
      new google.maps.LatLng(36.606, -118.0638),
      new google.maps.LatLng(36.433, -117.951),
      new google.maps.LatLng(36.588, -116.943),
      new google.maps.LatLng(36.34, -117.468),
      new google.maps.LatLng(36.24, -116.832)];
var distanceInMeters = google.maps.geometry.spherical.computeLength(path);
  1. create a google.maps.Polyline with your array of google.maps.LatLngLiterals, then call .getPath on that polyline.
var polyline = new google.maps.Polyline({
      map: map,
      path: path
var distanceInMeters = google.maps.geometry.spherical.computeLength(polyline.getPath());
  1. convert your coordinates to google.maps.LatLng and call compute distance on each pair, accumulating the distance.
var distanceInMeters = 0;
for (var i=0; i<path.length-1; i++) {
    distanceInMeters += google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(path[i].lat, path[i].lng),new google.maps.LatLng(path[i+1].lat, path[i+1].lng));
  1. write your own version of the haversine formula that takes an array of LatLngLiterals