back to krasimirtsonev.com
to blog's home page

GoogleMaps JS API: address to coordinates transformation

When we are talking about maps, Google is an absolute leader. Their GoogleMaps tool is free, well documented and works really good. What I didn't find directly in the documentation is how to get the exact location based on plain text. I.e. to convert an address to google.maps.LatLng object. That's why I wrote a simple function that did this job.

The page here demonstrates the method. It contains an input element, button and a map. Type something in the field and press search.

Step 1: Initialize the map



Step 2: Calling the method


I simply attached a listener to the onclick event of the button. The addressToLocation function accepts the address (as plain text) and a callback function which will operate with the results.

Step 3: Create google.maps.LatLng object based on the field's value


The method uses the google.maps.Geocoder object of the GoogleMaps API. At the end it sends the results to the callback function.

Step 4: Process the results


The callback function accepts only one parameter. It is actually an array of objects. Every object has three properties:
The function outputs all the locations in a div container, pans the map and adds markers for every item in the array.

The full source code is available here.

Sharing ...
Commenting ...
blog comments powered by Disqus