简体   繁体   中英

How can get the distances between 2 points via Google Maps Javascript API3?

I am developing an application via the Google Maps API (Version 3).

I have 2 google.maps.LatLng objects named loc1 and loc2 .

How do I calculate the distance between them in say meters?

I have tried using various tricks from this question to convert latitude/longitude measures into meters. However, I question the reliability of my implementation.

I have also tried implementing a distance matrix, but I think that a distance matrix is a lot of work just to calculate the distance between 2 points.

Thank you!

Sounds simple, I recommend the geometry library,

https://developers.google.com/maps/documentation/javascript/reference#spherical

computeDistanceBetween(from:LatLng, to:LatLng, radius?:number)

From my experience the result is in meters. Remember to add the optional geometry library in your tag

<script type="text/javascript" 
src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false">
</script>

Calculating distances between two points basically boils down to pythagoras (sum of the squares etc). However, this doesn't really work with Lat & Lon (which are coordinates on a sphere). What I do is convert the Lat & Lon values to the local map grid which is flat. Then I can use pythagoras to calculate the distance between those points. I've already posted on this in Stack Overflow here . This will have all the code you would need.

Your question is a bit ambiguous.

I mean - when you say the distance, do mean

  • distance in a straight line
  • or driving distance,
  • or bicycle distance,
  • or walking distance. The answer to this question will determine your implementation.

If it is a straight line distance you need, then it is best to use the haversine implementation. Otherwise, you will need to request directions from the google directions service, specifying the mode of "transport".

When you've finished you can test the distance between two points on a straight line using the provided map. It will give you a visual as well as the distance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM