Creating a Bing Maps v7 control Centred on an Address Rather than a known Latitude/Longitude

This was a question that came up at the cloudhack event last weekend – when you create a new instance of the Bing Maps AJAX control, you specify the centrepoint of the map in latitude and longitude coordinates, using the center property in the viewOptions passed to the constructor. For example:

var map = new Microsoft.Maps.Map( document.getElementById("mapDiv"),
                           { credentials: ENTERYOURBINGMAPSKEY,
                             center: new Microsoft.Maps.Location(54, -4),
                             mapTypeId: Microsoft.Maps.MapTypeId.aerial,
                             zoom: 12
                           });

(You can view more information on the viewOptions parameters here:  http://msdn.microsoft.com/en-us/library/gg427628.aspx )

However, what if you want to create a map centred on an address instead of a latitude/longitude coordinate? This seems like a fairly simple, common request, so I was a bit surprised to find that none of the Microsoft method reference guides nor any of the “interactive SDK” sites provide an example showing how to do this.

Fortunately, it’s not too tricky to do so, for the benefit of everyone other than those teams at the cloudhack event who asked me, I thought I’d write it up here😉

First, you need to geocode the address into latitude and longitude coordinates (using the REST Locations API is the easiest way to do so direct from javascript). Then, in the jsonp callback function that is executed after the geocode service returns its results, create and centre the map on the returned coordinates. Here’s an example (note that you will need to replace ENTERYOURBINGMAPSKEY here with some valid credentials, or else the call to the REST service will fail and the map will not be created):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
  <script type="text/javascript">
    var map = null;
    var credentials = "ENTERYOURBINGMAPSKEY";
    
    function GetMap() {
   
      // Define the address on which to centre the map
      var addressLine = "54 Chiswell Street"; // Street Address
      var locality = "London"; // City or town name
      var adminDistrict = ""; // County
      var country = "UK"; // Country, obviously
      var postalCode = "" //Postcode
       
      // Construct a request to the REST geocode service
      var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations" 
                           + "?countryRegion=" + country
                           + "&addressLine=" + addressLine
                           + "&locality=" + locality
                           + "&adminDistrict=" + adminDistrict
                           + "&postalCode=" + postalCode
                           + "&key=" + credentials
                           + "&jsonp=GeocodeCallback"; // This function will be called after the geocode service returns its results
       
      // Call the service
      CallRestService(geocodeRequest);
    }

    function GeocodeCallback(result) {
      // Check that we have a valid response
      if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) {
       
        // Create a Location based on the geocoded coordinates
        var coords = result.resourceSets[0].resources[0].point.coordinates;
        centerPoint = new Microsoft.Maps.Location(coords[0], coords[1]);

        // Create a map centred on the location
        map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),
                           { credentials: credentials,
                             center: centerPoint,
                             mapTypeId: Microsoft.Maps.MapTypeId.aerial,
                             zoom: 18
                           });
         
        // Add a pushpin as well
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter());
        map.entities.push(pushpin);
      }
    }

    // This is a generic function to call a REST service and insert the JSON
    // results into the head of the document
    function CallRestService(request) {
      var script = document.createElement("script");
      script.setAttribute("type", "text/javascript");
      script.setAttribute("src", request);
      var dochead = document.getElementsByTagName("head").item(0);
      dochead.appendChild(script);
    }      
  </script>
</head>
<body onload="GetMap();">
  <div id='mapDiv' style="position: relative; width: 400px; height: 600px;">
  </div>
</body>
</html>

Here’s the resulting map:

image

This entry was posted in Bing Maps, Spatial and tagged , , . Bookmark the permalink.

One Response to Creating a Bing Maps v7 control Centred on an Address Rather than a known Latitude/Longitude

  1. Mark Dathorne says:

    Thank you, Alastair! This was indeed just what i was looking for – a straightforward location map from postcode.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s