-1

Could you suggest any idea how to do the following task? I have the route from point A to point B. The route passes through several countries. How Can I calculate using Google Maps or alternative the distance of route part for each country?

Will be very appreciated for any ideas?

Alexey Zakevich
  • 131
  • 1
  • 1
  • 8
  • Do you have an idea of the country/ies it is likely to be? I did a bit of programming to determine if a point was within a countries bounds. Step 1 was to do a reverse geocode, and then check if the address contains the country I was looking at. If that failed, I checked if it was within very approximate bounds (rectangle) and then finally checked if it was inside a polyline path (more accurate). You could then determine the last point within a country and then calculate the distance. – Paul Thomas Mar 13 '17 at 09:21
  • 1
    Check this one: http://stackoverflow.com/q/28741923/1023562 along with working fiddle: http://jsfiddle.net/Daggett/zr89r8ws/ – Ivan Jovović Mar 13 '17 at 09:23
  • related question: [Google maps api v3 calculate mileage by state](http://stackoverflow.com/questions/34028829/google-maps-api-v3-calculate-mileage-by-state) – geocodezip Mar 13 '17 at 12:38
  • Ivan, thank you. Looks like we need. – Alexey Zakevich Mar 14 '17 at 03:41

1 Answers1

0

This should get you going, check fiddle here https://jsfiddle.net/yeoman/nm50vypx/1/ Basically do following:

1. Get latitude and longitude of FIRST point

2. Get latitude and longitude of SECOND point

3. User built-in API function google.maps.geometry.spherical.computeDistanceBetween()

var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);

alert(calcDistance(p1, p2));

//calculates distance between two points in km's
function calcDistance(p1, p2) {
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}

IMPORTANT: your script tag must have &libraries=geometry included in it.

For example <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=YOURKEYHERE&libraries=geometry"></script>

Another One line example

var latitude1  = 39.46;
var longitude1 = -0.36;
var latitude2  = 40.40;
var longitude2 = -3.68;
var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1,longitude1), new google.maps.LatLng(latitude2,longitude2)); 

EDIT: Distance results are expressed in meters

Danish
  • 1,467
  • 19
  • 28