[javascript] How to make an autocomplete address field with google maps api?

Using Google Maps API and JQuery I would like to have an Address field that when typing it will autocomplete the address entered there. How this could be achieved?

This question is related to javascript jquery google-maps

The answer is


There are some awesome libraries such as select2, but it doesn't match my need. I've made a sample from scratch in order to use a simple input text.

I only use bootstrap and JQuery, Hope it'll be useful: Example

HTML:

<div class="form-group col-md-12">
    <label for="address">Address</label>
    <input type="text" class="form-control" id="address">
</div>

<div class="form-group">
    <div class="col-md-4">
        <label for="number">number</label>
        <input type="text" class="form-control" id="number">
    </div>
    <div class="col-md-8">
        <label for="street">street</label>
        <input type="text" class="form-control" id="street">
    </div>  
</div>

<div class="form-group">
    <div class="col-md-4">
        <label for="zip">zip</label>
        <input type="text" class="form-control" id="zip">
    </div>
    <div class="col-md-8">
        <label for="town">town</label>
        <input type="text" class="form-control" id="town">
    </div>  
</div>

<div class="form-group">
    <div class="col-md-4">
        <label for="department">Department</label>
        <input type="text" class="form-control" id="department">
    </div>
    <div class="col-md-4">
        <label for="region">Region</label>
        <input type="text" class="form-control" id="region">
    </div>  
    <div class="col-md-4">
        <label for="country">Country</label>
        <input type="text" class="form-control" id="country">
    </div>  
</div>

JS:

$("input#address").suggest({
    label : "Adresse complete", 
    street_number_input : {
        id : "number",
        label : "Numero de la rue"
    },
    street_name_input : {
        id : "street",
        label : "Nom de la rue"
    },
    zip_input : {
        id : "zip",
        label : "Code postal"
    },
    town_input : {
        id : "town",
        label : "Ville"
    },
    department_input : {
        id : "department",
        label : "Departement"
    },
    region_input : {
        id : "region",
        label : "Region"
    },
    country_input : {
        id : "country",
        label : "Pays"
    }
});

Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.

Here's how you could do it if you could force people to bend to your will:

  1. User enters: postal (zip) code

    You fill: state, city (province, for Canada)

  2. User starts to enter: streetname

    You: autofill

  3. You display: a range of allowed address numbers

    User: enters the number

Done.

Here's how it is natural for people to do it:

  1. User enters: address number

    You: do nothing

  2. User starts to enter: street name

    You: autofill, drawing from a massive list of every street in the country

  3. User enters: city

    You: autofill

  4. User enters: state/provence

    You: is it worth autofilling a few chars?

  5. You: autofill postal (zip) code, if you can (because some codes straddle cities).


Now you know why people charge $$$ to do this. :)

For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa


I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.


It is easy, but the Google API examples give you detailed explanation with how you can get the map to display the entered location. For only autocomplete feature, you can do something like this.

First, enable Google Places API Web Service. Get the API key. You will have to use it in the script tag in html file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}

Like others have mentioned, the Google Places Autocomplete API is missing some important functions. Case in point, Google will not validate that the street number is real, and they also will not put it into a standardized format. So, it is the user's responsibility to enter that portion of the address correctly.

Google also won't predict PO Boxes or apartment numbers. So, if you are using their API for shipping, address cleansing or data governance, you may want one that will validate the building number, autocomplete the unit number and standardize the information.

Full Disclosure, I work for SmartyStreets


Below I split all the details of formatted address like City, State, Country and Zip code. 
So when you start typing your street name and select any option then street name write over street field, city name write over city field and all other fields like state, country and zip code will fill automatically. 
Using Google APIs.
------------------------------------------------
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function() {
    var places = new google.maps.places.Autocomplete(document
            .getElementById('txtPlaces'));
    google.maps.event.addListener(places, 'place_changed', function() {
        var place = places.getPlace();
        var address = place.formatted_address;
        var  value = address.split(",");
        count=value.length;
        country=value[count-1];
        state=value[count-2];
        city=value[count-3];
        var z=state.split(" ");
        document.getElementById("selCountry").text = country;
        var i =z.length;
        document.getElementById("pstate").value = z[1];
        if(i>2)
        document.getElementById("pzcode").value = z[2];
        document.getElementById("pCity").value = city;
        var latitude = place.geometry.location.lat();
        var longitude = place.geometry.location.lng();
        var mesg = address;
        document.getElementById("txtPlaces").value = mesg;
        var lati = latitude;
        document.getElementById("plati").value = lati;
        var longi = longitude;
        document.getElementById("plongi").value = longi;            
    });
});


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api