Showing Geolocation in Browser using HTML5 and JavaScript


Few days ago, we learned about “Easy Form Validation using HTML5”. Hope, you liked that post. Today we will explore another new great feature of HTML5 with complete code analysis and simple but easy to understandable demo.

 

HTML5 exposes geolocation API to get the geographical location of user. Today we will focus our discussion on this topic. So, continue reading.

 

HTML5 geolocation API is used to get the geographical location of a user. Using the navigator, user can retrieve the current location and you can pass that location to show that location in a Map.

 

The API supports the following browsers: IE9+, Firefox, Chrome and Opera.

 

To implement this in your web page, you need to follow the below mentioned steps:

    • Check whether the geolocation API is supported by the underlying browser.
    • If supported, call the navigator.geolocation.getCurrentPosition() method and if not supported, display a proper message to the user.
    • If the navigator.geolocation.getCurrentPosition() successfully retrieves the user’s current position, it returns a coordinate object to the function “showPosition” specified as first parameter passed to this method.
    • The showPosition() function displays the latitude and longitude of the current location.
    • Further enhance it to show the position in a map by using a map service like Google Map.

Here is the code snippet of the implementation:

 
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    }
    else { message.innerHTML = "Geolocation is not supported by this browser."; }
}
 
function showPosition(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var imageURL = "http://maps.googleapis.com/maps/api/staticmap?center="
    + latitude + "," + longitude + "&zoom=14&size=400x300&sensor=false";
 
    document.getElementById("locationHolder").innerHTML = 
                    "Your current location is: (" + latitude + ", " + longitude + ")";
    document.getElementById("mapHolder").innerHTML = "<img src='" + imageURL + "'>";
}

 

 

Don’t forget to handle the user interaction and error status properly. Based on the error code, show a proper message to the user. Here is the code snippet of the same, for your reference:

 
function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            message.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            message.innerHTML = "Location information is unavailable at this time."
            break;
        case error.TIMEOUT:
            message.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            message.innerHTML = "An unknown error occurred. Try again later."
            break;
    }
}

 

Hope, this code snippet is clear to you and you will now be able to retrieve the user location and show it using a map service. In our case, we used Google Map to pass the latitude and longitude to the API as shown above.

 

HTML5 Geolocation Demo

Let’s see a demo of the same. Click the button below to call the getCurrentPosition() method. Once it retrieves the location coordinate, it will show you the coordinate (latitude and longitude) in the page. Also, it will show you that position in Google map. Check it out here:

 

Click the button below to show your current position in map:

 

 

The complete code of the above implementation is mentioned here, for your reference:

 
<!DOCTYPE html>
<html>
<head>
    <title>HTML5 Geolocation Demo</title>
</head>
<body>
    <p id="message">Click the button below to show your current position in map:</p>
    <button onclick="getLocation()">Show Geolocation</button>
    <div id="locationHolder"></div>
    <div id="mapHolder"></div>
 
    <script language="JavaScript">
        var message = document.getElementById("message");
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            }
            else { message.innerHTML = "Geolocation is not supported by this browser."; }
        }
 
        function showPosition(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var imageURL = "http://maps.googleapis.com/maps/api/staticmap?center="
            + latitude + "," + longitude + "&zoom=14&size=400x300&sensor=false";
 
            document.getElementById("locationHolder").innerHTML = 
                        "Your current location is: (" + latitude + ", " + longitude + ")";
            document.getElementById("mapHolder").innerHTML = "<img src='" + imageURL + "'>";
        }
 
        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    message.innerHTML = "User denied the request for Geolocation."
                    break;
                case error.POSITION_UNAVAILABLE:
                    message.innerHTML = "Location information is unavailable at this time."
                    break;
                case error.TIMEOUT:
                    message.innerHTML = "The request to get user location timed out."
                    break;
                case error.UNKNOWN_ERROR:
                    message.innerHTML = "An unknown error occurred. Try again later."
                    break;
            }
        }
    </script>
</body>
</html>

 

 

I hope, this post will be helpful for you to understand the API and showing position in Google map. Let me know, if you have further queries on it. Don’t forget to share it to your network and help your friends to learn about it.

 

I am available in Twitter, Facebook and Google+. Don’t forget to connect with me for updates and technical discussions. Also, subscribe to my blog’s RSS feed and Email Newsletter to get the blog updates directly in your inbox. Cheers. Happy Coding.


8 comments

  1. Hello sir, if i implement the same in the windows 8 app, it just showing the error message as, user has denied the permission to share the location.. Its not asking the permission, can you help me with this..??

    ReplyDelete
  2. What's up, I want to subscribe for this website to take latest updates, therefore where can i do it please help.

    ReplyDelete
  3. First of all I want to say terrific blog! I had a quick question that I'd like to ask if you don't mind.

    I was curious to find out how you center yourself and clear your mind prior to writing. I've had difficulty clearing my mind in getting my ideas out there. I truly do enjoy writing however it just seems like the first 10 to 15 minutes are usually wasted just trying to figure out how to begin. Any suggestions or hints? Cheers!

    - Danhelen

    ReplyDelete
  4. This design is spectacular! You most certainly know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost. ..HaHa!)

    Excellent job. I really enjoyed what you had to say, and more than that,
    how you presented it. Too cool!

    ReplyDelete
  5. Hello, this is an excellent post.
    i am curious to know, how we can get the exact position in the map.
    for example, rather than getting the city name, i would like to know the street name within the city.
    Is there any way to get that using google maps api?

    Thanks

    ReplyDelete
  6. Thank you for the feedback. To get the exact position in the map, you have to find out the Google API in depth. They might have exposed something on that.

    ReplyDelete
  7. I have also bookmarked you for checking out new posts. Your post is very informative.

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top