David-IT
David-IT

Reputation: 165

Google Maps API JS - Place autocomplete with two combined fields

I come to you because I can not use the autocomplete place function instead of Google maps JS api v3 as I would like.

Indeed, I would like to implement autocompletion on a field by adding the value of another.

Concretely, I would like to have two fields, one for the company name, the other for the address. I would like autocompletion is performed only on the address fields but taking into consideration the company name.

So if I fill "Company XYZ" in the company field and "New York, USA" in the address, it should lookup "Company XYZ, New York, USA".

Classical example with one input :

Function JS :

function initialize() {
        // Create the autocomplete object, restricting the search
        // to geographical location types.
        autocomplete = new google.maps.places.Autocomplete(
                /** @type {HTMLInputElement} */(document.getElementById('addr')),
                { types: ['establishment', 'geocode'] });
        // When the user selects an address from the dropdown,
        // populate the address fields in the form.
        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            fillInAddress();
        });
    }

HTML Form :

<input class="field" id="company_name" />
<input class="field" id="addr" />

In your opinion is it possible? If so, how?

With thanks.

Upvotes: 4

Views: 3112

Answers (1)

MrUpsidown
MrUpsidown

Reputation: 22491

You can use the Autocomplete Service and get query predictions for the values of both fields.

See https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction

var autocompleteService = new google.maps.places.AutocompleteService();

getPlacePredictions(document.getElementById('company').value + ', ' + document.getElementById('address').value);

function getPlacePredictions(search) {

    autocompleteService.getPlacePredictions({
        input: search,
        types: ['establishment', 'geocode']
    }, callback);
}

Below is a full example of a custom autocomplete predictions list (styled based on Google implementation), with search highlighting, place details request and display on the map with a marker.

JSFiddle demo

Upvotes: 4

Related Questions