How to Get Current Address Using HTML 5 Geolocation and Google Maps API

fx-maps-mylocation

In my new plugin f(x) Maps, I create a location search with ability to get current address/location using HTML 5 Geolocation and Google Maps Geocoding API. And in this post I want to share how I did it.

Actually this plugin search feature is based on a lot more complex plugin I build for a client.

Why you need this?

This feature is super useful to build location-based web app. There’s a lot of what we can do with Google Maps API, I hope after reading this tutorial, it will open more ideas and possibilities to you.

This tutorial is going to be just code examples with console.log() results. You will need to find a way to use/implement it your-self.

1. HTML5 Geolocation

Basically, with HTML5 Geolocation we can get current user coordinate (latitude and longitude). You can read more at w3schools about it.

Here’s the code to ask user their current location:

navigator.geolocation.getCurrentPosition(
    function( position ){ // success cb
        console.log( position );
    },
    function(){ // fail cb
    }
);

You can put the code above in click event, example:

jQuery( document ).ready( function( $ ){

    $( "#get-mylocation" ).click( function(e) {
        e.preventDefault();
        navigator.geolocation.getCurrentPosition(
            function( position ){ // success cb
                console.log( position );
            },
            function(){ // fail cb
            }
        );
    });

});

And when user click that link, the browser will show “Share Location” prompt:

share-location

And if user share their location, from the console log we can get this data:

{
    coords: {
        accuracy : 20,
        altitude : 0,
        altitudeAccuracy : 0,
        heading : NaN,
        latitude : -6.981802600000001,
        longitude : 110.3978743,
    },
    timestamp : 1480324142770,
}

So, to get latitude and longitude data, we can do this:

var lat = position.coords.latitude;
var lng = position.coords.longitude;

2. Use Google Map API to format the Coordinate

To do this, you will need a Google Map API key. You can get it here.

And then load Google Maps JS in your page.

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&key={API KEY}&ver=3.exp"></script>

And then we need to load this coordinate using LatLng method in Google Maps JS:

var lat = position.coords.latitude;
var lng = position.coords.longitude;
var google_map_position = new google.maps.LatLng( lat, lng );

this will return a complex data from Google Map API about the location coordinates.

3. Google Map Geocoding API

We can use the data above in Google Map Geocoding API to get accurate information such as address, etc.

var google_maps_geocoder = new google.maps.Geocoder();
google_maps_geocoder.geocode(
    { 'latLng': google_map_pos },
    function( results, status ) {
        console.log( results );
    }
);

From the console log above we can get this data:

{
    address_components : {
        0 : 'street name',
        1 : 'city',
        2 : '..',
    },
    formatted_address : 'Nicely formatted address',
    geometry : {}
    place_id : '',
}

If what we need is simply the current address, we can get the formatted_address node using this code:

if ( status == google.maps.GeocoderStatus.OK && results[0] ) {
    console.log( results[0].formatted_address );
}

5. Chrome Browser and SSL

Chrome browser require SSL/HTTPS for HTML5 Geolocation. We can check first using this code:

var is_chrome = /chrom(e|ium)/.test( navigator.userAgent.toLowerCase() );
var is_ssl    = 'https:' == document.location.protocol;
if( is_chrome && ! is_ssl ){
    return false;
}

6. Final Code

So, here’s the final code from this tutorial:

jQuery( document ).ready( function($) {

    $( "#get-mylocation" ).click( function(e) {
        e.preventDefault();

        /* Chrome need SSL! */
        var is_chrome = /chrom(e|ium)/.test( navigator.userAgent.toLowerCase() );
        var is_ssl    = 'https:' == document.location.protocol;
        if( is_chrome && ! is_ssl ){
            return false;
        }

        /* HTML5 Geolocation */
        navigator.geolocation.getCurrentPosition(
            function( position ){ // success cb

                /* Current Coordinate */
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                var google_map_pos = new google.maps.LatLng( lat, lng );

                /* Use Geocoder to get address */
                var google_maps_geocoder = new google.maps.Geocoder();
                google_maps_geocoder.geocode(
                    { 'latLng': google_map_pos },
                    function( results, status ) {
                        if ( status == google.maps.GeocoderStatus.OK && results[0] ) {
                            console.log( results[0].formatted_address );
                        }
                    }
                );
            },
            function(){ // fail cb
            }
        );
    });


});

Follow me on twitter @turtlepod to get update about future tutorials.

Comment below, let me know if I miss something OR if you want more explanation about this tutorial.

And share this tutorial if you think it’s useful 🙂

3 Comments

  1. Al Lindas

    I am a beginner HTML5 student and am trying to use this code to find the user’s address. I cannot get it to work. I did add my own API key. Any help would be much appreciated.

Comments are closed.