I have Google Maps Autocomplete working on severalinput tags like this:
<input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />
To enable Google Maps auto-complete, I have the following code:
//https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
$(document).ready(function () {
autocomplete = new google.maps.places.Autocomplete((document.getElementById('pac-input')), { types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function () {
MyFunc();
});
});
And then, in the MyFunc() function I do what I need:
function MyFunc() {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = $(this);
//stuff that uses input
}
This code however, has two problems:
$(this) but it aint working. How can jQuery help me ?Thanks in advance!
You don't need jQuery for this. Here is a working example using only javascript:
HTML:
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text"></input>
JavaScript:
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
}
JSFiddle demo
If you want to do it with jQuery then you can try this way:
$('.autocomplete').each(function() {
var autocomplete = new google.maps.places.Autocomplete($(this)[0]);
autocomplete.inputId = $(this).attr('id');
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
});
JSFiddle demo
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With