Skip to content

Instantly share code, notes, and snippets.

@RadGH
Created April 23, 2017 20:01
Show Gist options
  • Save RadGH/3e937dbbfc93422e7058bdec5ea2815e to your computer and use it in GitHub Desktop.
Save RadGH/3e937dbbfc93422e7058bdec5ea2815e to your computer and use it in GitHub Desktop.
Google Maps JS API V3 - Get distance between two points in miles using the Geometry library.
/*
IMPORTANT:
You must edit the <script> for the Google Maps API to include the Geometry API library, by adding to the URL: &libraries=geometry
Example:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=geometry"></script>
*/
// Define two points using LatLng objects
var point_a = new google.maps.LatLng( 44.037307, -123.110091 );
var point_b = new google.maps.LatLng( 44.034851, -123.099449 );
// Get the distance between the two points in miles
var distance_miles = getDistanceInMiles( point_a, point_b );
// Show the distance, rounded to 2 decimals
alert( "The distance between point_a and point_b is: \n\n" + distance_miles.toFixed(2) + " miles" );
// Get distance in miles. The API returns distance in meters, and we can easily convert that with multiplication.
function getDistanceInMiles( point_a, point_b ) {
var distance_in_meters = google.maps.geometry.spherical.computeDistanceBetween( point_a, point_b );
return distance_in_meters * 0.000621371; // convert meters to miles
}
@doroudi
Copy link

doroudi commented Jul 21, 2018

thanks!

@ShunyangLi
Copy link

How to get the real distance by driving

@RadGH
Copy link
Author

RadGH commented Sep 18, 2018

How to get the real distance by driving

Not with this code. You'll need to look into the different maps apis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment