Get current location address in javascript

I originally thought grabbing a user's current location was going to be difficult, but it's actually very simple.

There's quick way on w3schools that shows us how to use HTML5 Geolocation API:
http://www.w3schools.com/html/html5_geolocation.asp

You also have to include the Google Maps API:
http://maps.googleapis.com/maps/api/js?sensor=false

Then you write your function to grab the current location:


function getLocation() { if(navigator.geolocation { navigator.geolocation.getCurrentPosition(geoSuccess, geoError); } else { alert("Geolocation is not supported by this browser."); } }
You'll also need to write your success function: function geoSuccess(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; alert("lat:" + lat + " lng:" + lng); } And then an error function: function geoError() { alert("Geocoder failed."); } You can stop here if you just want the lat and lng coordinates. But if you want to convert these coordinates to a full address, you can call another function that passes your lat and lng: Add a function in your success function: function geoSuccess(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; alert("lat:" + lat + " lng:" + lng); codeLatLng(lat, lng); } And here's the code for that function: var geocoder; function initialize() { geocoder = new google.maps.Geocoder(); } function codeLatLng(lat, lng) { var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({'latLng': latlng}, function(results, status) { if(status == google.maps.GeocoderStatus.OK) { console.log(results) if(results[1]) { //formatted address var address = results[0].formatted_address; alert("address = " + address); } else { alert("No results found"); } } else { alert("Geocoder failed due to: " + status); } }); } Answer found from: http://stackoverflow.com/questions/6797569/html5-geolocation-easiest-way-to-get-city-name

Get current location address in javascript

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:

Get current location address in javascript

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.

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 🙂

How can I get the current location of a user?

In order to get the current location of the user, we are going to use the getCurrentPosition() method which is available in the Navigator geolocation property. The getCurrentPosition() method is used for getting the current location of the user. Syntax: navigator.

How do I find the geolocation address?

On the Google Maps app, you can't pull up a context menu. To find the address for your coordinates, hold your finger down over the red pin that shows your coordinates. Then, after 1-3 seconds, the address will pop up on the bottom of your screen.

How can get current address in HTML?

So, to get latitude and longitude data, we can do this: var lat = position. coords..
navigator. geolocation. getCurrentPosition(.
function( position ){ // success cb..
console. log( position );.
function(){ // fail cb..

What is geolocation in Javascript?

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information. WebExtensions that wish to use the Geolocation object must add the "geolocation" permission to their manifest.