Geek alert…this is a very technical post.
Google Places covers tens of millions of place locations around the world. But what’s a place? A place is anything that answers the question “Where are you?” Restaurants, shops, landmarks, events, and much more. You can use it in the browser, from a server, or from a mobile device.
In our custom software web application we had the need to enter a street address and have it autocomplete into fields that we store in the database and utilize in other reports.
You will need several Javascript libraries. You need to go to https://cdnjs.com/libraries and get the following libraries. You will do the following steps:
- Browse the Libraries
- Search for the Library Name (twitter-bootstrap, jquery, etc.)
- Find the library you need.
- Hover over the file you need. For instance, bootstrap.min.js. Click on the copy and choose the “Copy Script Tag with SRI”
- Put into your file.
Cascading Style Sheet files needed:
- bootstrap.min.css
- font-awesome.min.css
- sweetalert.min.css
Javascript Libraries files needed:
- jquery.min.js
- popper.min.js
- bootstrap.min.js
- sweetalert.min.js
You will need a credential from Google Maps API. I don’t want to go into that level of detail here click here for instructions -> https://developers.google.com/maps/documentation/javascript/get-api-key
Using Bootstrap 4 the layout was created to have two columns, one column for each place.
To ensure good reusable and assignable code remember the following when creating these fields.
- Each “section” must have a unique identifier (i.e. “facility_address”, “source_address”)
- Each field that you type in the address must have the style class of “autocomplete”
- Each field has a style class that directly associates with the data that Google Places API returns (i.e. “street_number”, “route”, “country”, “administrative_area_level_1”)
Then I created a function to initialize the fields to the autocomplete function of Google Places.
function createGeoListeners(autocompletesWraps) {
var options = {types: ['geocode']};
var inputs = $('.autocomplete');
var autocompletes = [];
for (var i = 0; i < inputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(inputs[i], options);
autocomplete.inputId = inputs[i].id;
autocomplete.parentDiv = autocompletesWraps[i];
autocomplete.addListener('place_changed', fillInAddressFields);
inputs[i].addEventListener("focus", function() {
geoLocate(autocomplete);
}, false);
autocompletes.push(autocomplete);
}
}
A function to fill in the address fields.
function fillInAddressFields() {
$('.googleerror').removeClass('is-valid is-invalid');
var place = this.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
var val = place.address_components[i].long_name;
//console.log("address Type " + addressType + " val " + val + " pd " + this.parentDiv);
$('#'+this.parentDiv).find("."+addressType).val(val);
$('#'+this.parentDiv).find("."+addressType).attr('disabled', false);
}
}
The geolocate function is assigned at focus of the input to narrow down the addresses the user chooses from.
function geoLocate(autocomplete) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
And finally…a function to capture any errors from Google Places and highlight the field using a Sweet Alert.
function gm_authFailure() {
$('.gm-err-autocomplete').addClass('is-invalid');
swal("Error","There is a problem with the Google Maps or Places API","error");
};
You can see the code in action here -> http://lindarawson.com/blogartifacts/addressformtest.html
To download the code simply choose “View Source” and copy the code.
Thank you for this demonstration. I used it as a base for a project I’m working on.
You are welcome!
Just wondering how would you also add the Lat/Long?
GREAT ARTICLE !
I have used this script in my project and its work fine. Thanks for posting this great article . keep it up good work . Thanks
Hi Linda.
Great job but I have found a bug. If you filter by country adding for example var options = {types: [‘geocode’], componentRestrictions: {country: “ch”}};
and you input the ZIP code, the script don’t copy the city.
Any idea on how I can fix it ?
This doesn’t seem to work in IE.
Get the following:
SCRIPT5009: ‘google’ is undefined
Hello!
Wonderful article!
Loved it
I tested this example with few more blocks with inputs and it worked perfectly coz these blocks , and etc. were siblings
However when I separated those blocks from each other and put one of them inside modal window it stopped working,although the ID is still there in the array
Could you please let me know how can I solve this issue
Thank you
Cheers!