Saturday, January 19, 2013

Google Address AutoComplete Tutorial

This is very basic for google address lookup/auto completion tutorial.
First thing you need to do is include google maps javascript to your page.

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

Next step is to initialize Autocomplete. When you initialize Autocomplete, it basically starts a listener which listens for an input. Following code does that.

var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);

When you start typeing it looks like this.



When user selects an address, value of input field get updated to selected address. You do not need to have nay extra code. However in case if you want to read selected address, you will need to add "place_changed" google maps event listener. It returns PlaceResult object. Following code shows how you can get PlaceResult object.

google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
alert(place.formatted_address);

You can find a demo here: Google Address Auto Complete Demo In this example, I am loading address lookup form using an ajax.

You can download demo source from github: View source code


Here is the complete snippet.

10 comments:

  1. thanks a lot. I was looking for this indeed

    ReplyDelete
  2. Hey, it doesent work for me. I put the first four Lines into my Code, but when i type in the SearchField no Autocompletion appears.

    do you have an advice?

    ReplyDelete
  3. what if i want to add a new field into the autocomplete result?

    ReplyDelete
  4. Not working for me either.

    I can tell that the browser is asking google for the results, they are just not being displayed.

    ReplyDelete
  5. Which browser are you trying with? I just tested in chrome http://priyankgandhi.com/googleapi/ And it is working.

    ReplyDelete
  6. How to get Postal Code at end of each address?

    ReplyDelete
  7. Hey, this isnt working for me. If I place the exact code provided by you, I receive the following error:
    SyntaxError: missing : after property id
    $(function() {
    Can you please help?

    ReplyDelete
  8. Excelente Trabajo lo voy a implementar en:
    http://calimaframework.com

    ReplyDelete
  9. Podrian ayudarme en esto, http://es.stackoverflow.com/questions/8637/c%C3%B3mo-realizar-autocompletar-en-mi-cuadro-de-b%C3%BAsqueda


    he tratado de implementar que está en este post pero no logro dar solución.

    se los agradecere demasiado.!

    ReplyDelete