问题
For example I have a simple rout From Warsaw, Poland To Berlin, Germany by car. Now I can calculate distance of all route (572km). How I can calculate distance for each country? Germany ~ 100km and Poland ~ 472km.
I tried to detect country border using start_location for each DirectionsLeg in legs[] and detect country name by start_location. For example:
getCountry(legs[0]) => 'pl'
getCountry(legs[1]) => 'pl'
getCountry(legs[2]) => 'pl'
//border detected
getCountry(legs[3]) => 'de'
getCountry(legs[4]) => 'de'
It's work, but if route is so "big", getCountry() return OVER_QUERY_LIMIT.
UPDATED
Thanks Dr.Molle for help!
Working fiddle. Warning: Code works fine, but it's not optimized. Be carefully!
P.S. Sorry for my English
回答1:
You'll need a way which avoids requests for each step to detect the country .
There is a FusionTable which contains the boundaries for countries: https://www.google.com/fusiontables/data?docid=16CTzhDWVwwqa0e5xe4dRxQ9yoyE1hVt_3ekDFQ#map:id=3
Possible workflow:
request the geometries for the countries affected by the route. Using the path directly wouldn't work here, because the URL would be too long, so filter the results based on the bounds of the route(it may return more than the affected countries, but there is no other option)
a sample-query for the route warsaw-berlin would be:
SELECT sovereignt,json_4326 FROM 16CTzhDWVwwqa0e5xe4dRxQ9yoyE1hVt_3ekDFQ WHERE ST_INTERSECTS(kml_4326, RECTANGLE(LATLNG(51.88951,13.38593), LATLNG(52.52003,21.01219)))The RECTANGLE used in this query will be created based on the
bounds-property of the given route. Sample-request: http://jsfiddle.net/doktormolle/vexqe0ps/based on the returned geometries create an array of polygons(they must not be visible) for each country.
- Loop over the steps of the route, and for each step iterate over the polygon-array. Use
google.maps.geometry.poly.containsLocation()to check if the start_(or end_)location is placed within the current polygon. When it does, add the distance of the current step to the distance for the current country.
回答2:
I don't know if my method is faster than your getCountry() but I use the instruction text and search for "Entering" (as in e.g."Entering Germany") - that means you're at the border (but you must use the lat-lng of the next index)
var instr = myroute.legs[0].steps[i].instructions;
isBorder=instr.includes("Entering");
if(isBorder) {
// calculate partial distance with myroute.legs[0].steps[i+1].start_location.lat() etc;
}
EDIT: I just realized there's also an end_location, too, for every step so you don't need the next step as a reference to calculate the subdistance. Or simply use myroute.legs[0].steps[j].distance.value. Also, adding the distances of every step together eliminates the need to call any further functions.
来源:https://stackoverflow.com/questions/28741923/how-to-calculate-distance-for-each-country-using-google-maps-api-route