Bing Maps and code-behind
19/07/2011 Leave a Comment
I really struggled to automatically integrate Bing Maps into ASPX code behind. I found a solution, although I am not sure its the best available. This is how it is implemented.
In the page, add a ScriptManager to the top of the page.
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”></asp:ScriptManager>
Then add the div, and script blocks for the map. Note below we are also adding a handler onto the map, for when the map has finished drawing (‘viewchangedend’). The purpose of this, is when the map has moved, or zoomed, we will make a request for another set of data to overlay on the map.
<div id=’mainDisplay’ style=”position:relative; width:800px; height:400px;”></div>
<script type=”text/javascript” src=”http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0″></script>
<script type=”text/javascript”>function onviewchange() {
var latlon = map.getCenter();
var resp = PageMethods.MapMoved(latlon.latitude, latlon.longitude, onComplete);
}
function onComplete(result, response, context) {
eval(result);
}var map = new Microsoft.Maps.Map(document.getElementById(‘mainDisplay’), { credentials: ‘————————});
var attachmapviewchange = Microsoft.Maps.Events.addHandler(map, ‘viewchangeend’, function (e) {onviewchange(e);});
</script>
The PageMethods.XXXX line is the key, what this does is call the code behind method, with the same signature.
Here is the matching code-behind, in this case rendering a pin in the center of the map, each time the map moves. The code is returned to the page, and evaluated. The pin includes the handler to reset the popup and update its location and its title / description. Information on how to do this, is scarce and it took me quite a few attempts. I also found that the line infobox.setLocation(e.entity.getLocation()) does a great job of crashing Visual Studio during debug.
[WebMethod]
public static string MapMoved(float lat, float lon) {// Do interesting things here, like make a call to a web service …
javaScript = “map.entities.clear();” +
“var infobox = new Microsoft.Maps.Infobox(map.getCenter(),” +
“{title: ‘Title’,” +
“description: ‘Description’, ” +
“visible: false});” +
“map.entities.push(infobox);”;javaScript += “var pushpin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(” + lat + “,” + lon + “), null);” +
“Microsoft.Maps.Events.addHandler(pushpin, ‘click’, function(e) { ” +
“infobox.setOptions({visible:true});” +
“infobox.setOptions({title:’ The title ‘});” +
“infobox.setOptions({description:’ Description Contents ‘});” +
“infobox.setLocation(e.target.getLocation());” +
” }); ” +
“map.entities.push(pushpin);”;return javaScript;
}


