Using HTML 5 Geo Location in an ASP.NET MVC Bing Maps Application (Part 2)

Posted by: Sumit Maitra , on 1/5/2012, in Category ASP.NET MVC
Views: 161088
Abstract: In this article, we will see a very simple use case of using HTML 5 Geo-Location API from the spec along with Bing Maps in an ASP.NET MVC app.

In the first part, we saw how to retrieve HTML 5 Geo-Location in an ASP.NET MVC app using the built in API and JavaScript.

When talking about Geo-Location, it’s difficult to keep Maps out. Fortunately for us, both Bing and Google have a very extensible Mapping framework already available for us to use. Today we will use Bing’s Ajax based mapping framework to calculate driving directions between the user and center of San Jose, CA and also visualize it on the Map.

Before we start using the mapping framework, you need to login to the Bing Maps developer portal and get an API Key. You can login using any Live Id like your Hotmail account. With that minor logistics out, we’ll go pedal-to-metal with code.

Using the Bing Maps Ajax Control and API

In this example, we are going to solve a hypothetical problem where we are building the ‘Directions’ page for a super-store.

  • We know the address to our super-store and for simplicity sake, there is only one address.

  • We will request user to allow us access to the geo-location API

  • If user gives us access, great! We’ll calculate the route using Bing’s API and show the route between user’s detected location and the super-store on a Bing map.

  • If user does not give us access, we will request them to provide us with an Address and try to get the directions between the two locations.

Let’s walk through the steps to build this application.


Step 1: Create new ASP.NET MVC project in Visual Studio.

Step 2: Edit Index.cshtml add the following elements to it.


- Update the Heading to ‘Directions to Super Market’.

- <div> container with id askPermission contains the elements that ask user for access to location information and get their input.

- <div> container with id manualEntry contains the elements to get address manually and a button to fire off the search.

- <div> container with id mapContainer has two child <div> elements. One shows the Bing Map control and the other the Direction details.

This is all the HTML we need. Next the JavaScript magic:

Step 3: Add the following script reference to pull in the Bing map dependencies

<script type="text/javascript" src=""></script>

Step 4: Now we start adding our presentation logic to manipulate the map as per user input.


The jQuery document load shortcut initializes required global variables i.e. the

  • map – object that holds the instance of the Bing Map.

  • directionManager - object that manages directions between two points,

  • location - User’s location (if detected by location service) and

  • STORE_LOCATION - Address of our hypothetical store (that has an ‘elaborate’ address of San Jose, CA, USA. Change it to a city of your choice and locality)

Next we hide the <div> container for manual entry and we hook up the click event handler for the ‘Yes’ button through which user gives us permission to use location services.

  • We hide the <div> container that had the request for permission.

  • Next we call the loadMap() method that we will see below.

  • Next we create an options object requesting the location API to enable high Accuracy if possible, set a time out of 20 seconds and maximum age of the value to 2 seconds. The Accuracy and maximumAge are more important from the prospect of tracking a moving location and is kind of redundant here.

  • Finally we call the API to get the location placing two callbacks to handle success and failure.

The loadMap() method simply checks if the map object has been initialized or not and if not initialize it. Couple of things to note here

  • We pass the <div> element that is supposed to contain the map.

  • We pass credentials in form of our API key that we obtained from Bing Maps portal.


For now, we will follow the path where user has allowed our app to access location services. We will come back to the second path once this path is completed.

- The showPosition(…) method is called once the location is retrieved successfully.

  • The input param is checked for null and if not null, the map is setup to center at that location.

  • Thereafter we check if our directionsManager has been initiated or not. If not, the Directions module is actually loaded handed a callback method that creates the directionManager.

- The createDirectionsManager callback initiates directionManager and adds two handler methods, one for success and one for failure. Currently we are not doing anything in this as seen in the code for directionsUpdate() and directionsError(args) methods

- Finally we call the createDrivingRoute(location) method to draw the route on the map itself.


The createDrivingRoute(coords) method calculates the route between the user location and the static address and gets the Map control to draw it for us.

- It checks if directionManager is instantiated and if not instantiates it.

- Next it reset directions (if any were previously set)

- Next it sets the routeMode to driving. Other possible modes are public transport and walking.

- Next it checks if coordinates passed to the method are null

  • If not null is creates the first waypoint using the coordinates’ latitude and longitude values

  • If it is null it assumes the from address is provided by user manually and uses that as the starting address

- Next it sets up the destination point using the static address STORE_LOCATION.

- Next the direction manager is passed the element that it should use to render the direction details.

- Finally the direction manager calculates the directions and adjusts the map accordingly.

At this point we are pretty much done with the presentation logic for the auto detect path. Next we look at the code that handles the manual address entry path


- First we have the ‘No’ button click handler. This is where the user tells us they don’t want to share location automatically

  • It simply hides the question and shows the manual entry panel.

- Next we have the ‘Get Directions’ button click handler that essentially calls the following two methods

  • loadMap() – Simply load the map object if not loaded already

  • showPosition(null) – By passing null to showPosition, we are implying we don’t have the exact location thus the createDrivingRoute method eventually uses the text provided by user in the address text box.

All Set, let’s run the solution!

The home page comes up as follows


If I click Yes and Allow access, I get the following


You can try out all the possible combinations.

In Conclusion

We saw a very simple use case of using HTML 5 Geo-Location API from the spec along with Bing Maps in an ASP.NET MVC app. The links in the reference section has a sample site of possible Bing Map applications. On the other side, we have the simple Location API that’s powerful, but to be successful, the user needs to be softly introduced to it so that they trust you and your application.

Have fun and let us know what creative solutions you come up with the location API.

Browser Compatibility

The code has been tested to successfully show the map and directions on following browsers: Internet Explorer 9, Firefox 9.0.1, Chrome 16.0.912.63 m


To demonstrate the geo-location API we have explicitly called to get the browser’s location API. The Bing Maps control contains an alternate mechanism to get user location as well.


W3C Spec for Location API in browsers -

Bing Maps Sample Playground -

Bing Maps API Registration -

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

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

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 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 Book 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 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!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

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

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Test Papers on Friday, January 13, 2012 4:57 AM
Your information is very useful for me.
Comment posted by Amit on Monday, February 6, 2012 3:03 AM
I am looking for certification, and i found a website called they are providing certification at just 1875, and some other certification in IT domain so sir please confirm me
Comment posted by Akit on Monday, February 13, 2012 5:31 AM
Hi ,
         Hi! Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store.
Comment posted by Mike on Sunday, February 1, 2015 11:06 AM
Your tutes are both understandable and useful.  I love your mag.
Comment posted by Suprotim Agarwal on Monday, February 2, 2015 4:22 AM
Thanks Mike. Glad to hear that :)






jQuery CookBook