I have Google Map and two inputs. Both of them use autocomplete, like this:
//first input autocomplete
var input1 = (document.getElementById('start'));
var autocomplete1 = new google.maps.places.Autocomplete(input1);
autocomplete1.bindTo('bounds', map);
//second input autocomplete
var input2 = (document.getElementById('end'));
var autocomplete2 = new google.maps.places.Autocomplete(input2);
autocomplete2.bindTo('bounds', map);
After I fill both of these inputs I'm displaying the shortest way betweeen them using Directions API:
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
My inputs look like this:
<input type="text" id="start" onchange="calcRoute();" />
<input type="text" id="end" onchange="calcRoute();" />
The Problem:
Everything works perfectly fine if I type full addresses in these inputs for example:
Berlin, Germany & Hamburg, Germany (I guess that's because every letter typed triggers onchange()).
But when I type:
Berlin, Germany and then Hamb > click on Hamburg from Google Autocomplete Dropdown List
It doesn't show Hamburg, it shows a town called Hamb.
Is there any way to fix it?
autocompleteTo = new google.maps.places.Autocomplete(
(document.getElementById('end')),
{types: ['geocode']}
);
google.maps.event.addListener(autocompleteTo, 'place_changed', function () {
calcRoute();
});
Listening to the place_changed event is much more efficient then triggering a route recalculation on every change of the input field.
来源:https://stackoverflow.com/questions/18690444/google-maps-autocomplete-directions-api-trigger-onchange-for-dropdown-li