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:

  1. Browse the Libraries
  2. Search for the Library Name (twitter-bootstrap, jquery, etc.)
  3. Find the library you need.
  4. Hover over the file you need. For instance, bootstrap.min.js. Click on the copy and choose the “Copy Script Tag with SRI
  5. 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.

Two Columns of Places
HTML Screen for Two Columns of Addresses

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”)
Multiple Google Places Setup
Multiple Places Setup

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.