HTML 5 Geo-Location in ASP.NET MVC Web Apps (Part 1)

Posted by: Sumit Maitra , on 1/2/2012, in Category ASP.NET MVC
Views: 127063
Abstract: In this article, we will see how to retrieve Geo-Location in an ASP.NET MVC and HTML 5 app using the built in API and JavaScript.

Before we get started with HTML5 Geo-Location, let’s dispel a common misunderstanding: Geo-Location is a part of HTML5 spec! It’s not! Geo-Location has it’s own independent specification. You can read about the latest spec here. The split actually happened after HTML5 started with Geo-Location built in. But somewhere down the road, Geo-Location was deemed fit enough to be a spec of it’s own. Fortunately for the devs, all the major browsers like IE8+, Firefox, Chrome and Opera support the specification.

With that trivia aside, let’s take a closer look at Geo-Location.

 

Specifications of Retrieving User Location – A birds’ eye view

User location tracking through IP addresses has been around forever. However what were missing was a nice clean abstraction and a certain level of user acceptance to the fact that they were sharing their location to the outside world. The Geo-Location spec has provided that abstraction.

For the developer there is a nice clean way on how to leverage the user’s location and for the end-user there is the re-assurance that they are in control of the information sharing.

Geo Location is achieved pretty much using one or more of the following (at the same time):

  1. Mapping through IP address. This is not a very accurate method and may be completely wrong if you are using a VPN to tunnel all your Internet traffic. However if you are not using VPN and sitting a home, it can get to city level accuracy pretty easily.
  2. Getting GPS information directly. If the computer running the browser has built in GPS hardware like most smart phones today, the geo-location can be narrowed down pretty well.
  3. Wireless: Wireless routers locations help triangulate positions too.

The spec mandates that, the browser must give an opportunity to the user to opt out of the location tracking. Thus it makes geo-location a safe experience for the user and a transparent and easy API for the developer.

Geo-location identification can be actually used to enhance a users experience in many ways. Few examples are:

  1. In a social networking site, you can highlight what’s going around in the vicinity
  2. In a mapping application, you give users a head start if they are looking for directions
  3. In business applications, you can identify how the user can reach you by listing out the places nearby. A banking application may list out the ATMs and branches nearby
  4. As fraud detection mechanism, you can ask users for additional information if you detect the user is at a location that’s too far off his ‘home’ location. For example if a user from US is having his account accessed from somewhere in Africa, you may want to throw up additional challenge questions, after they have provided the correct password. Now if the user is rightfully on an African Safari, they will be able to answer the challenges and your system will note this new location down a possible location, that user uses.

Whatever usage you deem fit, always remember, sharing location is still a matter of concern for most people online. So lead them into it as gently as possible, by providing as much helpful information up front as possible. Directly using the Geo-Location API on load of your site, may not be the friendliest way to tell users you want to use their location. A better introduction would be serving them a reason and also explaining exactly what you do with the location information.

If they chose to trust you, good! You can help them. If they don’t, you have to be prepared.

With the theory out of the way, let’s get down to some code.

Using the HTML 5 Geo-location API in an ASP.NET MVC app

Create a new ASP.NET MVC Application and select ‘Internet Application’

Open the Views\Home\Index.cshtml and add the following markup:

html5-geolocation

The above markup does the following:

  • Adds a couple of labels and text boxes to hold the Latitude and Longitude retuned by the geo-location call
  • Adds a snippet of JavaScript that uses jQuery to execute on page load completion.

The first line navigator.geolocation.getCurrentPosition(…,…) makes the API call. These are async calls and they take call back methods that handle the result action. We have two call back methods, one for success called showPosition and another for error called positonError

The position object has the obvious properties – latitude and longitude. Other properties include

  • accuracy – a value indicating the perceived accuracy of the position
  • altitude – a value indicating altitude of the position (if available)
  • altitudeAccuracy – an optional value indicating perceived accuracy of the altitude (if available)
  • heading – heading of the position (if available)
  • timestamp – time stamp when the location was retrieved.

Now you are ready to run the app. When your default browser comes up, you will notice it asks the user for permission in one form or the other.

For eg: IE 8+ shows a banner at the bottom like the following

ie8-geolocation

It allows user to ‘Allows always’ and ‘Deny always’ as well. If they do ‘Deny always’, your site will never be able to use the Geo-Location service for that user until they go back into Internet options and remove your site from the filter.

Firefox displays the following:

firefox-geolocation

If user selects ‘Share Location’, you are given one time access; ‘Always Share’ means full-time access and Never Share means no access.

Once you select ‘Share Location’, you will see there is a slight pause and then the location textboxes will populate.

Don’t be surprised if two browsers come up with slightly different numbers. As mentioned earlier, the mechanism for detecting location is open in absence of GPS hardware and since my laptop doesn’t have any GPS hardware, the fall back mechanisms are not hard bound to any browser and thus the variation.

Here is what I see - Firefox vs IE9

html5-ie-vs-firefox

Designing a fallback for HTML 5 Geolocation

When Geo Location service is refused by user or errors out

In the above sample, we saw the happy path where the browser was able to retrieve the location. But we also need to handle scenarios, where user said No or Never.

For this case, we have the positionError callback method. The position object has a code property that gets the following values

Code = 0: Unknown Error
Code = 1: Permission Denied – User refused to let your application access geo-location information. Here is where you give the user to enter some data that helps you with where they are  - like an Address zip or pin code.
Code = 2: Position not available – The geo-location api failed to get the location
Code = 3: Time out – The geo-location request timed out

When Geo Location service isnot available in Browser

Also like all things on the web, we need a fallback for those corner cases where user hits our site with an unsupported browser and the Geo-Location service fails.

This is easy, we can just wrap the geo-location fetch code inside a check like this:

if(navigate.geolocation)
{
// try to geo – locate user
}
else
{
// Browser doesn’t support geo-location
}


With the above in mind, we revise our code to ask user if it’s okay to use Geo Location and also handle the fallback scenarios. Update Index.cshtml as follows

Ask Users if they want to share their location

geolocation-permission

Wrap the location fields inside a region that can be hidden if required

autolocation

Add a field that allows user to provide Zip/Pin code as a fallback

manuallocation

Associate click handlers for the Yes and No buttons

Associate click event handlers for the Yee/No buttons and hide the right <div> as per user action. Also note the options JSON object that has three parameters, enableHighAccuracy, timeout (in milliseconds), and maximumAge (in milliseconds for which the location value should be considered valid).

The showNoLocation method hides the latitude/longitude fields and makes the manual zip entry field visible.

show-no-location

Show Position and Handle Error

geolocation-error

The showPosition method is a callback for a successful Geo-Location call. The positionError method handles the error conditions and in our case we silently show the user the field to enter zip code by calling the showNoLocation function.

The next step

With the basics out of the way, in the next part we will do something a little more involved that uses some of the best practices we talked above in an ASP.NET MVC web app. Stay tuned for the next article!

Update: Here's the next part of this series: Using HTML 5 Geo Location in an ASP.NET MVC Bing Maps Application (Part 2)

The entire source code of this article can be downloaded
over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Sumit is a .NET consultant and has been working on Microsoft Technologies since his college days. He edits, he codes and he manages content when at work. C# is his first love, but he is often seen flirting with Java and Objective C. You can follow him on twitter at @sumitkm or email him at sumitkm [at] gmail


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Simple Asp on Friday, January 6, 2012 3:39 PM
Can you provide a similar example in  asp.net without the   MVC Web Apps ?plz ..it would be great help !
Comment posted by Sothi on Saturday, January 7, 2012 9:12 AM
Great Article. Thanks
Comment posted by Sumit on Saturday, January 7, 2012 1:54 PM
@Simple Asp - There is practically no server side code in this sample. If you added the javascript to an HTML file it would work as is.

@Sothi - Thanks, glad you enjoyed it.
Comment posted by Remove Hard Water Stains on Sunday, January 8, 2012 6:32 AM
I fell very much greatfull for your kind information related to this subject.It makes me aware about this matter.your articale related to this matter is very
much informative and up to date.
Comment posted by ms bill terror on Sunday, January 8, 2012 7:27 AM
hi,
   I noticed HTML5 version supports geo location of IP. Then we don't need to buy IP location package from third parties.
Comment posted by Humayun Rashed on Friday, April 6, 2012 1:59 AM
This is fine. but not showing the actual location. why..?
Comment posted by vineetha on Thursday, July 19, 2012 1:28 AM
pls post a similar project without MVC
Comment posted by mike on Friday, August 3, 2012 12:18 PM
Dude, posting code as a screenshot is a disrespect to the readers.
Comment posted by Admin on Monday, August 6, 2012 5:05 AM
Sorry Mike can't help as it helps prevent plagiarism to a certain extent
Comment posted by gfhf on Wednesday, March 19, 2014 3:12 AM
fghf

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel