Google Maps - plot lines and distance (as the crow flies) between multiple latitude longitude pairs

22,883

Solution 1

Plotting a route "as the crow flies" is easy, just set polyline's geodesic option to true:

var geodesic = new google.maps.Polyline({geodesic: true});

You can use this example: http://code.google.com/apis/maps/documentation/javascript/examples/geometry-headings.html

To calculate the distance, you can utilize geometry library of the Google Maps API V3. http://code.google.com/apis/maps/documentation/javascript/geometry.html

The calculation is simple:

var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngOfPointA, latLngOfPointB);

To compute the length of a path you can use computeLength function:

var path = geodesic.getPath();
var length = google.maps.geometry.spherical.computeLength(path)

Solution 2

Be sure to include the geometry library in your call to Google Maps API.

Bootstrap from Documentation

<script type="text/javascript"       src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=true_or_false">  </script>
Share:
22,883
Danny
Author by

Danny

Senior Developer at Reckless - a digital agency based in Chester, UK.

Updated on October 30, 2020

Comments

  • Danny
    Danny over 3 years

    I'm looking to plot a route "as the crow flies" on a map via multiple latitude longitude pairs. I also need to calculate the total distance (and preferrably distance between points).

    I have found this example http://www.daftlogic.com/projects-advanced-google-maps-distance-calculator.htm but it is far more complicated than I require - I don't need any kind of search functionality, as I already have my latitude longitude data. However, the way it displays the route is what I'm looking to achieve

    Are there any simpler examples out there that I can build upon or any general guidance on achieving this?