简体   繁体   中英

Android: how to get the walking distance between two geo coordinates?

I used this query URL

http://maps.google.com/maps?q=from+A+to+B&output=kml

,which is given in the answer to this question . But after I tried it, it doesn't work with coordinates. It works with address names tho. I guess I could use google's geocoding to get the addresses first. But I wonder if there is another way to get the walking distance between two coordinates?

My New Answer :)

Use the Google Directions API .

It should be possible to make a request to http://maps.google.com/maps/api/directions/<json|xml>?<params> and specifying the coords as origin and destination parameter. I briefly tried it but it returned no results. Along their docs it should work, but they don't explain in detail how to specify latitude and longitude. But they say it's possible. Quote:

[...] origin (required) — The address or textual latitude/longitude value from which you wish to calculate directions [...]

Nevertheless, this should get you started. I would suggest going with the JSON output format. It's much simpler to parse and should use up less bandwidth (it's less verbose as XML).

It works: Here's an example URL: http://maps.google.com/maps/api/directions/json?origin=49.75332,6.50322&destination=49.71482,6.49944&mode=walking&sensor=false

My Previous Answer

The straight line distance can easily be determined using the Haversine formula. If you retrieve the route from Google, then you could calculate the distance of each segment and sum them up.

A while back, I wrote down the (well-known) algorithm ( Haversine ) in a blog post ( python and pl/sql )

Here's the copy of the python code:

from math import sin, cos, radians, sqrt, atan2

    def lldistance(a, b):
   """
   Calculates the distance between two GPS points (decimal)
   @param a: 2-tuple of point A
   @param b: 2-tuple of point B
   @return: distance in m
   """
   r = 6367442.5             # average earth radius in m
   dLat = radians(a[0]-b[0])
   dLon = radians(a[1]-b[1])
   x = sin(dLat/2) ** 2 + \
       cos(radians(a[0])) * cos(radians(b[0])) *\
       sin(dLon/2) ** 2
   #original# y = 2 * atan2(sqrt(x), sqrt(1-x))
   y = 2 * asin(sqrt(x))
   d = r * y

   return d

Translating this to Java should be trivial.

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