I am trying to get first result from the google map autocomplete field on blur event as well as place_changed from autocomplete field and partially succeed in it.
But I have facing a problem, when blur event get fired, I am getting the first result from the first option in autocomplete field, but the result is not proper, so I am not getting the exact lat long.
For example if I search for the word "Nimblechapps" The result is from place_change event is "Nimblechapps Pvt Ltd, Prahlad Nagar, Ahmedabad, Gujarat, India", but when blur event fired the result is what I am getting is "Nimblechapps Pvt LtdPrahlad Nagar, Ahmedabad, Gujarat, India". You can see the difference in both the results. There is a small deference of comma after Pvt. Ltd.
Below is my code to achieve it. I have taken reference from here
autocomplete = new google.maps.places.Autocomplete((document.getElementById('location')),{types: []});
google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChanged);
$('#location').on('blur', function () {
var firstResult = $(".pac-container .pac-item:first").text();
geocoder.geocode({"address": firstResult}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
infoWindow.close();
marker.setVisible(false);
var place = results[0];
if (!place.geometry) {
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12);
}
$('#lat').html(place.geometry.location.lat());
$('#long').html(place.geometry.location.lng());
$('#fLat').val(place.geometry.location.lat());
$('#fLong').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
console.log(place.geometry.location.toString());
if (place.address_components)
{
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(', ');
}
$('#location').val(firstResult);
infoWindow.close();
infoWindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infoWindow.open(map, marker);
infoWindow.close();
}
});
});
Edit : var firstResult = $(".pac-container .pac-item:first").text();
I am getting wrong result here in firstResult variable