Google Maps Places Api V3 Autocomplete - Select First Option On Enter (and Have It Stay That Way)
This question relates to the answer for this one: Google maps Places API V3 autocomplete - select first option on enter. Basically, it is to make the field use the first suggestion
Solution 1:
Try this: http://jsfiddle.net/pbbhH/60/
Basically abstracted the selection logic to a new function selectFirstResult(). Then called this function on both pressing enter and losing focus on text.
functionselectFirstResult() {
infowindow.close();
var firstResult = $(".pac-container .pac-item:first").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("input").val(firstResult);
}
});
}
EDIT: made minor change per @Ben's comment below.
Solution 2:
This is right but if u press enter and you have already selected an item this will select the first. So use this code:
functionselectFirstResult() {
infowindow.close();
if ( $('.pac-selected').length < 0){ // this linevar firstResult = $(".pac-container .pac-item:first").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("input").val(firstResult);
}
});
}
}
Post a Comment for "Google Maps Places Api V3 Autocomplete - Select First Option On Enter (and Have It Stay That Way)"