Using Google Places Autocomplete with Google Maps

05 February, 2014 by Tom Elliott

Google Places Autocomplete JavaScript Library is a great tool which suggests locations and points of interest through an AJAX style drop down meny based on user input. I’ve used this for a couple of recent development projects such as www.twitjobseek.com.

Places Autocomplete library hooks up to Google Maps JavaScript API V3 and does not require the use of an API Key.

This post runs through the steps involved to setup a basic autocomplete lookup functionality and how the returned values for longitude and latitude might then used to update a Google Map.

You can check out a Places Autocomplete demo, which includes a breakdown of the main parameters returned (such as the longitude and latitude).

The HTML

First things first, lets load the places library by putting the below line somewhere in the head tag (or in the footer if you prefer). This is in fact the same code required for standard Google Maps V3 functionality but with the added ‘places’ library

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=places"></script>

Then we can add some simple HTML for a locations input box, submit button and form, along with a div that will be used for our map. Using javascript:void(0); prevents the form from being submitted (which is not needed for the purposes of this demo).

<form action="javascript:void(0);" name="form1" id="form1">
	<input type="text" name="location" class="textbox" id="location" value="" />
	<input type="submit" value="Submit" class="submit" />
</form>
<div id="map-canvas"></div>

The JavaScript

Add the below JavaScript just before the closing body tag. This is so that we can access any of the HTML elements straight away without having to put everything within a ‘ready’ or ‘load’ handler.

The script does the following:

  1. Initiate the autocomplete method and a declare some variables
  2. Setup a Google Map and drop a basic marker on London
  3. Find the longitude and latitude values of the selected place on form submit
  4. Update the Google map marker and map center using the new longitude and latitude.
<script type="text/javascript">
	//Autocomplete variables
	var input = document.getElementById('location');
	var searchform = document.getElementById('form1');
	var place;
	var autocomplete = new google.maps.places.Autocomplete(input);

	//Google Map variables
	var map;
	var marker;

	//Add listener to detect autocomplete selection
	google.maps.event.addListener(autocomplete, 'place_changed', function () {
        place = autocomplete.getPlace();
        //console.log(place);
    });

    //Add listener to search
	searchform.addEventListener("submit", function() {
		var newlatlong = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
		map.setCenter(newlatlong);
		marker.setPosition(newlatlong);
		map.setZoom(12);

	});
	
	//Reset the inpout box on click
	input.addEventListener('click', function(){
    	input.value = "";
    });



    function initialize() {
	  var myLatlng = new google.maps.LatLng(51.517503,-0.133896);
	  var mapOptions = {
	    zoom: 1,
	    center: myLatlng
	  }
	  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

	  marker = new google.maps.Marker({
	      position: myLatlng,
	      map: map,
	      title: 'Main map'
	  });
	}

	google.maps.event.addDomListener(window, 'load', initialize);

</script>

Hooray, now we have a basic and unstyled Google Places Autocomplete drop down hooking up to a regular Google Map. 🙂

To elaborate this code further; first we declare our variables; the input field, form and a variable ‘place’ to hold our returned values from Places Autocomplete. An ‘autocomplete’ variable is also created to hold the API values of the returned location.

An event listener is setup as a Google Maps event to detect when a new Place is selected, based on the input field. console.log will let you see the output of this object in your browser’s JavaScript console, allowing you to drill down to see each parameter within the object. To access the longitude and latitude values for example, we can use place.geometry.location.lat() and place.geometry.location.lng().

A listener is also added to the form to detect when the form is submitted. This then updates the marker and center of the Google Map based on the selected location’s longitude and latitude values.

The Google Map itself is setup on load through the initialize() function, using the longitude and latitude of the center of London to setup the map and marker center. Zoom is 1 so we can see everything.



12 Comments

  • Black Thorn says:

    I want to fill out a form with the results you display at the end of your input but without having to hit submit. Where would I get the information as a result to do this?

    • Tom Elliott says:

      Hi, yeah you would need to replace the searchform eventlistener with whatever trigger you need to get the results in your form. For example an ‘on change’ trigger on a text field.

      • Black Thorn says:

        Do you know if there is a way to identify when someone clicks on one of the suggested result addresses?

        • Tom Elliott says:

          Hi, yes – when someone selects an address, it should be the google.maps.event.addListener(autocomplete.. listener that picks up this change/click, so you could try putting the longitude/latitude code here instead

  • Hi Tom, Thanks for the tutorial..
    I try to implement the source code, but whi i always get Uncaught TypeError: Cannot call method ‘addEventListener’ of null? Do you know?

  • Hey Tom Great tut!
    I love little spitting twitter bird too!

    I have a quick question, say i use Google autocomplete to bind to a map from an input field, how can i grab the autocomplete data that was place in the input field after the selected it from the drop. I have been trying to do that for a mad minute now, lol. I want to basically take the data from the input and copy it to another field.

  • Alexander Obuhovich says:

    Hitting ENTER while on suggested search result will submit the form before the google response with place object will return.

    Any ideas on how to fix that?

  • nivetha says:

    Hi!!
    When I click the submit button its not showing google map?why

  • Jan Erik says:

    How can I implement this on a wordpress page?

    Thanks!

  • Gerry says:

    Hey Tom, very handy thank you. What would tie nicely into this is how to get the browser to detect the ‘myLatLong’ coordinates automatically?