Autocomplete Places Search Box using Google Maps JavaScript API


autocomplete-places-search-box-google-maps-javascript-api-codexworld

Are you want to add an autocomplete address search box to your website? This article will help you alot. Here you will show the simple way to integrate location search box with autocomplete and display a map marked with selected location and info window.

Using Google Maps JavaScript API and Places library, you can easily add an autocomplete places search box to a web page. We’ll use HTML and JavaScript to implement places search box with autocomplete address suggestion. In the example script, a search box will display with a Google map. When the user begins to enter an address, an autocomplete suggestion dropdown will appear from where the user can select a location. Once a place is selected, respective location map would appear with marker and info window. Also, the full address, postal code, country, latitude & longitude will display under the Google Map.

HTML

The following HTML contains search input box, map container, and geo data container.

<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
<div id="map"></div>
<ul id="geoData">
    <li>Full Address: <span id="location"></span></li>
    <li>Postal Code: <span id="postal_code"></span></li>
    <li>Country: <span id="country"></span></li>
    <li>Latitude: <span id="lat"></span></li>
    <li>Longitude: <span id="lon"></span></li>
</ul>

JavaScript

Google Maps JavaScript API need to be loaded with Places library. Use libraries=places parameter and define a callback function (callback=initMap) when you load the API.

<script>
function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });
    var input = document.getElementById('searchInput');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
    });

    autocomplete.addListener('place_changed', function() {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Autocomplete's returned place contains no geometry");
            return;
        }
  
        // If the place has a geometry, then present it on a map.
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }
        marker.setIcon(({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);
    
        var address = '';
        if (place.address_components) {
            address = [
              (place.address_components[0] && place.address_components[0].short_name || ''),
              (place.address_components[1] && place.address_components[1].short_name || ''),
              (place.address_components[2] && place.address_components[2].short_name || '')
            ].join(' ');
        }
    
        infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindow.open(map, marker);
      
        //Location details
        for (var i = 0; i < place.address_components.length; i++) {
            if(place.address_components[i].types[0] == 'postal_code'){
                document.getElementById('postal_code').innerHTML = place.address_components[i].long_name;
            }
            if(place.address_components[i].types[0] == 'country'){
                document.getElementById('country').innerHTML = place.address_components[i].long_name;
            }
        }
        document.getElementById('location').innerHTML = place.formatted_address;
        document.getElementById('lat').innerHTML = place.geometry.location.lat();
        document.getElementById('lon').innerHTML = place.geometry.location.lng();
    });
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>

You can specify a Google API key using key=Your_Google_API_Key parameter when loading the Google Maps JavaScript API.

<script src="https://maps.googleapis.com/maps/api/js?key=Your_Google_API_Key&libraries=places&callback=initMap" async defer></script>

CSS

The following CSS is used to design in the example script.

#map {
    width: 100%;
    height: 400px;
}
.controls {
    margin-top: 10px;
    border: 1px solid transparent;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    height: 32px;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#searchInput {
    background-color: #fff;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    margin-left: 12px;
    padding: 0 11px 0 13px;
    text-overflow: ellipsis;
    width: 50%;
}
#searchInput:focus {
    border-color: #4d90fe;
}

1 Comment

  1. LE TUAN ANH Said...

Leave a reply

Connect With CodexWorld