Data, Maps, Usability, and Performance

HTML5 GeoLocation Address Form Filler

Last updated on October 10, 2012 in Development

HTML5 GeoLocation Address Plugin

I have recently filled out an address form and realized that HTML5 GeoLocation could really improve this user experience. Why do I have to fill in my city, state and zip when the browser can figure this all out with the GeoLocation API. Actually, the browser can only retrieve your Geo coordinates but I have already blogged about converting latitude and longitude coordinates to a street address via various APIs. So, it only makes sense to put in a button on an address form which would allow the end user to retrieve that information programmatically. Sure, the street address could be off sometimes but you can always correct the form instead of writing everything from scratch. So, let’s do it.

First, we have to consider that retrieving your GeoLocation is asynchronous, which is a little painful, but it makes sense because it takes some time to process this request and you don’t want to stop browser JavaScript execution. The painful part is in passing the form field where you want to put the result but if you are just doing this for one form then it should not matter (I wanted to provide two examples). So, I built two HTML forms, one with just a textarea and the second example with separate inputs for street, city, state, and zip. I attached the click event handlers and set a selector array so that it can be used later on to tell the putInDom function where to put the result. Normally we would just pass the selector to the function but we can’t do that because of the async callback. I use an array because I am either working with one ID (for the textarea) or multiple IDs for different form address fileds.

Look at the code above. The getLocation function tries to retrieve the browser’s location (it will probably ask you to accept or deny the request). When it receives this information, we move to the getAddress function (async callback). From there, we use the latitude and longitude coordinates to make an Ajax call to Google API so that we can retrieve the address for our geolocation. Unfortunately, this API call does not allow Cross Domain Access (no JSONP or CORS) so we have to do it server-side. Fortunately, Ben Alman has a simple PHP proxy that we could leverage. If the XHR request comes back with a 200 status code and there is a result, we pass it to the putInDom function. There, depending on the selector, we put the address result into the DOM.

Check out the Find My Address via HTML5 GeoLocation Demo. Here is the source code in a zip file. Now, I just want everyone to start using this because it is a nice improvement and saves me time. Thoughts?

Tags: , , , , ,

Facebook Twitter Hacker News Reddit More...