Bet I can guess your address! Reverse Geocoding with HTML5 & Google

Written by
Published
Updated
Typical Read
5 minutes
Find your next web developer job
Drupal Web Developer at On Fire Media (San Antonio, TX)

No, this isn't one of those bet I can guess your weight or age games you find at places like carnivals and Six Flags. I bet you I can guess your approximate address with HTML and reverse geocoding.

No, this isn’t one of those bet I can guess your weight or age games you find at places like carnivals and Six Flags. I bet you I can guess your approximate address with HTML and reverse geocoding.

Last month I wrote an article on the HTML5 Geolocation API. I’m going to take what I showed you there, expand on it and show you how to take advantage that powerful API and the Google Maps JavaScript API to perform reverse geocoding to find an approximate address.

See it in action!

Turning geographic data like a street address and zip code into geographic coordinates such as latitude and longitude is called geocoding

The process of turning geographic data like a street address and zip code into geographic coordinates such as latitude and longitude is called geocoding. When you do the opposite, turning coordinates into an address, it’s called reverse geocoding.

I know, I know, it’s not perfect, but it’s a lot closer than we had which at most times was somewhere in the city, state and sometimes just country. And granted, if the user doesn’t allow us to grab their location we’re back to using the IP, but it’s still a pretty good guess. Now only if we could have got Osama Bin Laden to visit one of our webpages while logged on as himself… long shot, but wouldn’t that be awesome if that’s how it went down.

In order to guess your user’s approximate address, just take what we learned in the HTML5 Geolocation Guide to get the user’s latitude and longitude using the HTML5 Geolocation API. Add a little pitch of the Google Maps JavaScript API and BAM! We’ll have a pretty good guess at where their located.

Download Demo Files

The HTML

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Reverse Geocoding with HTML5 &amp; Google Demo | Ben Marshall</title>
  </head>
  <body>
    <input type="button" class="button" id="go" value="Click Me and I'll Guess Your Address!">
    <div id="results"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="http://j.maxmind.com/app/geoip.js"></script> <!-- For our fallback -->
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="script.js"></script>
  </body>
</html>

All basic stuff, nothing too exciting. Just ensure you load the jQuery library, MaxMind GeoIP API for our fallback and the Google Maps JavaScript API. And of course, the script we’ll write below.

The JavaScript

script.js

$(document).ready(function () {
  // wire up button click
  $('#go').click(function () {
    // test for presence of geolocation
    if(navigator && navigator.geolocation) {
      // make the request for the user's position
      navigator.geolocation.getCurrentPosition(geo_success, geo_error);
    } else {
      // use MaxMind IP to location API fallback
      printAddress(geoip_latitude(), geoip_longitude(), true);
    }
  });
});
 
 
function geo_success(position) {
  printAddress(position.coords.latitude, position.coords.longitude);
}
 
function geo_error(err) {
  // instead of displaying an error, fall back to MaxMind IP to location library
  printAddress(geoip_latitude(), geoip_longitude(), true);
}
 
// use Google Maps API to reverse geocode our location
function printAddress(latitude, longitude, isMaxMind) {
    // set up the Geocoder object
    var geocoder = new google.maps.Geocoder();
 
    // turn coordinates into an object
    var yourLocation = new google.maps.LatLng(latitude, longitude);
 
    // find out info about our location
    geocoder.geocode({ 'latLng': yourLocation }, function (results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
      if(results[0]) {
        $('#results').fadeOut(function() {
          $(this).html('<p><b>Abracadabra!</b> My guess is:</p><p><em>' + results[0].formatted_address + '</em></p>').fadeIn();
        })
      } else {
        error('Google did not return any results.');
      }
    } else {
      error("Reverse Geocoding failed due to: " + status);
    }
  });
 
  // if we used MaxMind for location, add attribution link
  if(isMaxMind) {
    $('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP to Location Service Provided by MaxMind</a></p>');
  }
}
 
function error(msg) {
  alert(msg);
}

A Deeper Look

If you’ve already, I suggest you read my other post on HTML Geolocation to familiarize yourself with 90% of the code above. The rest is fairly simple to understand. You get the coordinates from getCurrentPosition() , then pass them to a printAddress() function, which uses the Google Maps API to perform the reverse geocoding.

The printAddress() function begins by creating a new Google Geocoder object. The Geocoder object gives us access to the geocode() method, which can take in a variety of options and return information based on them.

In this case, we’re using the google.maps.LatLng() method to create a new Google LatLng object that is passed into geocode() in order to get the address. The geocode() method is asynchronous, just like getCurrentPosition(), so we define an inline JavaScript function to handle the callback.

The callback’s response contains two parameters, one for the results and the other for the status code. If the status is OK, then it’s safe to parse the array of GeocoderResults objects stored in the results variable. The results variable is an array since Geocoder may return more than one entry.

Next, check for a GeocoderResults object in the first position of the array and, if it exists, append the formatted_address property to the defined results element.

For more information about reverse geocoding, check out Google’s documentation.

Wrapping Up

screenshot_meetways

The possibilities are limitless with what you can do with this functionality. Internet marketers are biting at the bit to start using this technology to drive even better user-specific ads to the eyes of millions. Online game developers like Parallel Kingdom are building ground-breaking web-based massive multiplayer online (MMO) games. With a little extra code, we can turn our code into a mobile app that gives user’s the ability to send their location to a friend or family member with a click of a button. Our imagination has now become the limit with what we can build. The next fives years is sure to be an exciting time in the web development arena bringing the whole world a better internet. Are there any projects you’ve done you can share that use the HTML5 Geolocation API?

Did you find Bet I can guess your address! Reverse Geocoding with HTML5 & Google useful? Get articles in your inbox.

…and don’t worry, I hate spam as much as you. Expect to hear from me at most once a week.

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on facebook

Stay updated.

Get a weekly email with the latest trends in web development & SEO.

Write a guest post.

Have an interesting article or idea? Become a guest blogger & pitch me your concept today.

1 comment on “Bet I can guess your address! Reverse Geocoding with HTML5 & Google”.

# May 18, 2016

this code work perfectly in localhost but real server is deos not working why problem

Join the conversation.

Your email address will not be published. Required fields are marked *

All comments posted on 'Bet I can guess your address! Reverse Geocoding with HTML5 & Google' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.