DotNetCurry Logo

HTML5 Geolocation API - Getting Started

Posted by: Pravinkumar Dabade , on 10/5/2015, in Category HTML5 & JavaScript
Views: 7478
Abstract: Using HTML5 Geolocation API to get the current geographical location of the user

Geolocation is one of the first HTML5 features that has been embraced across all major browsers. In this article, we will take a quick look at the HTML5 Geolocation API and learn how to access a user’s Geolocation.

 

Using HTML5 Geolocation API, you can share your current location with trusted web sites or even use it to provide additional geo location features in your own website, like providing discounts to visitors of your city etc. Finding out a visitor’s current location can be done using various methods. For example –

  • Find location using IP address
  • Wireless network connection
  • Using GPS etc

Note: None of these methods are accurate. For eg: A user can spoof IP address by using a Proxy and hence the location will be that of the Proxy and not the user.

In HTML5, we can fetch Latitude and Longitude using JavaScript. We can make use of the global “navigator.geolocation” object to do so. Using the latitude and longitude of Geolocation, you can then share your location, for example with apps like Google Maps.

We will explore this further with an example. I am using the free Visual Studio Community for this demonstration although you can use any web editor of your choice. We will first create an empty web application using Visual Studio and add support for jQuery and Modernizer in our project using NuGet package. Right click your project in Solution Explorer and click on “Manage NuGet Packages” and install jQuery and Modernizer in your project.

nugetpack

Now we will add a HTML page with the name MyLoc.html. Change the title to “HTML-5 GeoLocation API Test” and add the jQuery and Modernizer script reference into your HTML page. The Page should look like the following –

html1

Let’s design the HTML page. Add the following code in the body tag –

design

 


It’s time to check whether your browser supports the Geolocation API or not. For this we can make use of the Modernizr library. We will also write some code for fetching the latitude and longitude using jQuery. Let’s write the following code before the body tag ends –

<script> 
 $(function () { 
     var error = $('#errDiv'); 
     $('#btnFindLoc').click(function () { 
         if (Modernizr.geolocation) { 
             navigator.geolocation.getCurrentPosition(currentPosition, positionError); 
         } 
         else { 
             error.html("GeoLocation API of HTML 5 is not supported"); 
         } 
     }); 

     function currentPosition(currentPos) { 
         var coordinates = currentPos.coords; 
         $('#lati').text(coordinates.latitude); 
         $('#longi').text(coordinates.longitude);
        var googleMap = $('#gMap'); 
         googleMap.attr("href", "http://maps.google.com/maps?q=" + coordinates.latitude + "," + coordinates.longitude); 
     } 

     function positionError(errCode) { 
         switch (errCode.code) {
            case 0:
                error.html("Unknown Error - has occured"); 
            break;
            case 1:
                error.html("Permission Denied - By the user"); 
            break;
            case 2:
                error.html("Position/Location Unavailable"); 
            break;
            case 3:
                error.html("Timeout"); 
            break;
        }  
     } 
 }); 
 </script>

In the above script, we are using the jQuery DOM Ready function to ensure that the script executes after the page has loaded. A better way is to write the script just before the closing body tag.

On the button click, we are detecting the Geolocation support using Modernizr.geolocation. If your browser supports Geolocation, we call getCurrentPosition(success,fail) method. The currentPosition function fetches the Latitude and Longitude of the current location which in turn is passed to Google Maps.

When you call the getCurrentPosition method, the browser will not send your physical location to the web server. You will have to grant permission explicitly to do so. In IE 9.0+, you will see a permission dialog box as shown below –

ie-permission
Once you allow the information to be exposed, the code sets the “href” attribute value of anchor tag with Google Maps URL. When you click on the hyperlink, it will show you your location on Google Maps as shown below [Please note that this is my current location, in your case, Google maps will show you your location based on your coordinates]–

mycurrent-location


The positionError() function deals with possible exceptions which may arise during the execution of our code. And that’s all there is to test the Geolocation API.

Conclusion

In this article, we saw how to access/get the current geo location of the user using HTML 5 – Geolocation API.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Author
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!