Geocoding a Location

Bing
 

You are not viewing the latest version of the Bing Maps Web control (AJAX). Bing Maps V8 Web Control is the recommended JavaScript control for Bing Maps.

To geocode and reverse-geocode locations, you can use the geocode and reversegeocode methods in the SearchManager Class class. The class reference page provides sample code to show you how.

For most scenarios, you can use the geocode and reversegeocode methods in the SearchManager Class class to geocode and reverse-geocode locations. However, you also have the option to use the Bing Maps REST Services Locations API.

The following sections show how to create an AJAX V7 map session that geocodes a location and displays it on a map using the REST Services.

Note that the example code uses a session ID instead of a Bing Maps Key to make requests. It is best practice to use a session ID instead of Bing Maps Key to make your service request because it makes billable requests non-billable. The session ID must be created from the Bing Maps Key you used to load the map control. For more information about session IDs and transactions, see Using the REST Services with .NET and Understanding Bing Maps Transactions.

Before you add geocoding functionality, initialize the map using the following code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <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;

         function GetMap()
         {
            // Initialize the map
            map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId:Microsoft.Maps.MapTypeId.road}); 

         }

      </script>
   </head>
   <body onload="GetMap();">
      <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
   </body>
</html>

For this sample, add a text box and a Geocode button. In your script, create a ClickGeocode function that is called when the button is clicked.

<input id="txtQuery" type="text" value="Portland"/>
<input type="button" value="Geocode" onclick="ClickGeocode()"/>       

Since the Bing Maps REST Services also require a Bing Maps Key, you need to first retrieve the key from the map object to ensure the session is valid. Use the getCredentials method of the Map Class to do this. The getCredentials method takes a function to call when the credentials are retrieved.

function ClickGeocode(credentials)
{
   map.getCredentials(MakeGeocodeRequest);
}

Next, make a geocode request to the Bing Maps REST Services using the value in the txtQuery input box and the credentials.

The Bing Maps REST Services can return an XML or JSON response object. For JavaScript code, JSON is more appropriate, so set output=JSON. This means that you need to also set a jsonp callback function name. In this sample the callback function is named GeocodeCallback. Finally, since you do not know if the text provided is a place name or an address, supply the locationQuery parameter and set it to the value of the txtQuery text box. Your REST geocode request looks like this:

var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURI(document.getElementById('txtQuery').value) + "&output=json&jsonp=GeocodeCallback&key=" + credentials;

Now add script to make the REST request.

function MakeGeocodeRequest(credentials)
{
   var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURI(document.getElementById('txtQuery').value) + "&output=json&jsonp=GeocodeCallback&key=" + credentials;

   CallRestService(geocodeRequest);
}

function CallRestService(request) 
{
   var script = document.createElement("script");
   script.setAttribute("type", "text/javascript");
   script.setAttribute("src", request);
   document.body.appendChild(script);
}
function GeocodeCallback(result) 
{   
   // Do something with the result
}

Finally, add code to the GeocodeCallback function to set the map view to the found location and add a pushpin at that location. The final code is shown below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <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;

         function GetMap()
         {
            // Initialize the map
            map = new Microsoft.Maps.Map(document.getElementById("mapDiv"),{credentials:"Your Bing Maps Key", mapTypeId:Microsoft.Maps.MapTypeId.road}); 

         }

         function ClickGeocode(credentials)
         {
            map.getCredentials(MakeGeocodeRequest);
         }

         function MakeGeocodeRequest(credentials)
         {

            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations?query=" + encodeURI(document.getElementById('txtQuery').value) + "&output=json&jsonp=GeocodeCallback&key=" + credentials;

            CallRestService(geocodeRequest);
         }

         function GeocodeCallback(result) 
         {
            alert("Found location: " + result.resourceSets[0].resources[0].name);

            if (result &&
                   result.resourceSets &&
                   result.resourceSets.length > 0 &&
                   result.resourceSets[0].resources &&
                   result.resourceSets[0].resources.length > 0) 
            {
               // Set the map view using the returned bounding box
               var bbox = result.resourceSets[0].resources[0].bbox;
               var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
               map.setView({ bounds: viewBoundaries});

               // Add a pushpin at the found location
               var location = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
               var pushpin = new Microsoft.Maps.Pushpin(location);
               map.entities.push(pushpin);
            }
         }

         function CallRestService(request) 
         {
            var script = document.createElement("script");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", request);
            document.body.appendChild(script);
         }

      </script>
   </head>
   <body onload="GetMap();">
      <div id='mapDiv' style="position:relative; width:400px; height:400px;"></div>
      <input id="txtQuery" type="text" value="Portland"/>
      <input type="button" value="Geocode" onclick="ClickGeocode()"/>       
   </body>
</html>
Show: