HTML 5 Geo-Location in ASP.NET MVC Web Apps (Part 1)
Posted by: Sumit Maitra
in Category ASP.NET MVC
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):
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.
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.
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:
In a social networking site, you can highlight what’s going around in the vicinity
In a mapping application, you give users a head start if they are looking for directions
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
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:
The above markup does the following:
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
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:
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
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:
// try to geo – locate user
// 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
Wrap the location fields inside a region that can be hidden if required
Add a field that allows user to provide Zip/Pin code as a fallback
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 Position and Handle 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
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce the The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this eBook aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and the C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!