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.
Step 3: Add the following script reference to pull in the Bing map dependencies
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
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
- 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.
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.
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 - http://www.w3.org/TR/geolocation-API/
Bing Maps Sample Playground - http://www.bingmapsportal.com/isdk/ajaxv7
Bing Maps API Registration - http://www.bing.com/toolbox/bingdeveloper/
The entire source code of this article can be downloaded over here