Tuesday, May 7, 2013

Bing Maps for Silverlight – Get Current Location

I was using Bing Maps in a Silverlight application and I wanted to get current browser location. So I needed to call JavaScript code from the Silverlight .NET code. For that in Silverlight we have System.Windows.Browser namespace, which will provide classes which enables the interaction between managed code and JavaScript in Silverlight-based applications.

I have a Silverlight application and in my MainPage.xaml, I have a Map which I named as “MyMap”. This is the logic of what I am going to do to get the current browser location.
  1. Expose all the managed code objects, which I am going to access from JavaScript  In this case is’s “MyMap” and “Microsoft.Maps.MapControl.Location”.
  2. Find the location coordinates of the browser using JavaScript.
  3. Create a Microsoft.Maps.MapControl.Location object inside JavaScript and fill it’s latitude and longitude properties with the current location coordinates.
  4. Find my Silverlight object in the browser and inside my Silverlight object, find “MyMap” and set it’s location and zoom level.
Now lets see this in action. So before you can invoke any managed code from JavaScript, you first need to register the objects you want to expose to the browser.
HtmlPage.RegisterScriptableObject("MyMap", MyMap);
Since I want to create a Microsoft.Maps.MapControl.Location object inside java script  I am Registering Location as a managed type so it is available for creation from JavaScript code.
HtmlPage.RegisterCreateableType("Location", typeof(Location));
Now I have two JavaScript functions.
function GetUserLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(SetMapPosition);
    }
}
 
function SetMapPosition(position) {
    var location = document.getElementById('MySilverlightObject').Content.services.createObject("Location");
    location.Latitude = position.coords.latitude;
    location.Longitude = position.coords.longitude;
    document.getElementById('MySilverlightObject').Content.MyMap.Center = location;
    document.getElementById('MySilverlightObject').Content.MyMap.ZoomLevel = 10;
}
Here this is what happens.
  1. Check if Geolocation is supported.
  2. If supported, run the getCurrentPosition() method.
  3. If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter which is SetMapPosition.
  4. The SetMapPosition() function will get my silverlight object. Inside silverlight object, sets the properties to MyMap object which I have exposed to the browser from the code behind.
This is output. Since I am in Colombo, Sri Lanka, Map is zoomed to Colombo.
Untitled1
Default Map
Untitled2
My Location
I have uploaded a full sample to my SkyDrive.



Happy Coding.

Regards,
Jaliya