Google Maps Api - Retrieve The Road Distance Between 2 Coordinates
Solution 1:
First off, it is not recommended to use latlng coordinates in Directions API request as it may affect the location accuracy of the origin and destination. So therefore, I would suggest using the formatted_address instead.
Since you want to use Places API with 2 input fields, start and end location input fields, you will need to make a two instance of Places API. For example:
var startAutocomplete = new google.maps.places.Autocomplete(startInput);
var endAutocomplete = new google.maps.places.Autocomplete(endInput);
You will need to get the values from the getPlace()
method. In this case, I stored the formatted_address
value in a startValue
and endValue
variable which later on you will pass to directions service. The formatted_address
value of both start & end location is sufficient to serve as the origin
and destination
respectively.
var startValue, endValue;
startAutocomplete.addListener("place_changed", function() {
startValue = startAutocomplete.getPlace().formatted_address;
});
endAutocomplete.addListener("place_changed", function() {
endValue = endAutocomplete.getPlace().formatted_address;
});
For the DirectionsService
, you can use the values you got from the getPlace()
method like this:
directionsService.route({origin:startValue,destination:endValue,travelMode:"DRIVING"}
You can check out the example I made here on codesandbox.io to get a better view on how to do this on JavaScript. As a bonus I also added the alternativeRoutes
function which will display the fastest and shortest routes.
NOTE: you need to use your own API key on the example to work.
Post a Comment for "Google Maps Api - Retrieve The Road Distance Between 2 Coordinates"