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.
- 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”.
- Find the location coordinates of the browser using JavaScript.
- Create a Microsoft.Maps.MapControl.Location object inside JavaScript and fill it’s latitude and longitude properties with the current location coordinates.
- 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));
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;
}
- Check if Geolocation is supported.
- If supported, run the getCurrentPosition() method.
- If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter which is SetMapPosition.
- 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.
Default Map |
My Location |
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment