Google Maps - Autocomplete & Directions API - trigger onchange() for dropdown list?

守給你的承諾、 提交于 2019-12-22 10:44:49

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!