Google trends Public Holidays Coupon Code Code Compiler

How to make an autocomplete address field with google maps api

Jan 21, 2019

How to make an autocomplete address field with google maps api

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. We're going to be building a basic run-of-the-mill address form you've likely seen on thousands of sites. However, we're going to use the Google Maps and Places JavaScript APIs to autofill the form when the user types in either the street address

CSS Code:

			text-align: center;
			width: 800px;
			margin: auto;
			height: 30px;
			width: 355px;

HTML Code:

    <div class="wrapper">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"/>

JavaScript Code:

var placeSearch, autocomplete;
      var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        country: 'long_name',
        postal_code: 'short_name'

      function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);


      // Bias the autocomplete object to the user's geographical location,
      // as supplied by the browser's 'navigator.geolocation' object.
      function geolocate() {
        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

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

<script src="" async defer></script>

Copyright 2024. All rights are reserved