R0b0tn1k
R0b0tn1k

Reputation: 4306

Google Maps API: Getting different directions from what google maps provides?

I have this code:

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({ 'map': map }); 
var request = {
  origin:'42.0045384 21.4112488',
  destination:'41.997056 21.435871',
  travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
  }
});

It's supposed to get directions from 2 GPS points. It does that. But the problem is, the directions are wrong. The starting point is no where near to what it says. Have a look at this image: https://i.sstatic.net/f9sCi.png The actual coordinate for marker A is near the green man icon. So i typed in the same exact coordinates in Google maps, and i get this: https://i.sstatic.net/y02jH.png Those are the correct directions. So if it works on Google maps, why aren't the same coordinates working on the API?

Upvotes: 0

Views: 127

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117324

You are using origin and destination with string-parameters, there is no guarantee that these parameters will be used as LatLng, the provided strings must somehow be translated to LatLng's (usually by geocoding). When you geocode the query for origin you will see that you get the wrong position: http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/v3-geocoder-tool.html#q%3D42.0045384%2021.4112488

I guess Google Maps not simply geocodes the query, it detects that this query may be a LatLng and uses it as a LatLng instead of an address.

The solution is simple, when you know that both parameters are LatLng's, use them as LatLng's and you will get the desired result:

var request = {
  origin:      new google.maps.LatLng(42.0045384,21.4112488),
  destination: new google.maps.LatLng(41.997056,21.435871),
  travelMode:  google.maps.TravelMode.DRIVING
};

Upvotes: 1

Related Questions