Technology

Using Jquery with the Bing Maps REST API

Anthony Marshall
Anthony Marshall
10 Oct 2010
blog post featured image

In the last few months Bing Maps have released a new version of the web services (previously available as SOAP). This new version uses the increasingly popular REST format which for the first time allows us to use these services direct from javascript on the clients browser.

If you are creating rich, client side applications, using Jquery then these new REST APIs are a great way to do various mapping related tasks without having to load data from your own server side code. In this article we will show you a simple example of geocoding (finding a physical geographical location from its address or name) using Jquery and the Bing Maps REST API.

Getting started

To get started you need to create a simple HTML page and have the Bing Maps REST API reference site open for the location service  (https://msdn.microsoft.com/en-us/library/ff701715.aspx).

The first thing we need to do is add the script reference to the latest version of Jquery, in this case we are loading it from the Google CDN.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="https://www.w3.org/1999/xhtml" >
  3. <head>
  4.     <title>Bing Maps REST with Jquery</title>
  5.     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  6. </head>
  7. <body>
  8.  
  9. </body>
  10. </html>

 

Now we need to add a textbox for the user to type their location in, and a button to submit the user request.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="https://www.w3.org/1999/xhtml" >
  3. <head>
  4.     <title>Bing Maps REST with Jquery</title>
  5.     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  6. </head>
  7. <body>
  8.     <label for="myaddress">Type an address:</label>
  9.     <input type="text" id="txtAddress" />
  10.     <input type="button" id="btnSearch" value="Find Location" />
  11. </body>
  12. </html>

 

Now we need to add somewhere to display the results of our query.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="https://www.w3.org/1999/xhtml" >
  3. <head>
  4.     <title>Bing Maps REST with Jquery</title>
  5.     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  6. </head>
  7. <body>
  8.     <label for="myaddress">Type an address:</label>
  9.     <input type="text" id="txtAddress" />
  10.     <input type="button" id="btnSearch" value="Find Location" />
  11.     <p id="results"></p>
  12. </body>
  13. </html>

 

Wiring things up

Now we have the basic page created we need to start using Jquery to wire everything up. Lets start by adding the basic jquery to wire up a click event to the button on page load. For the sake of readability we will miss out most of the HTML in the snippet below.

  1. <script type="text/javascript">
  2.     $(document).ready(function () {
  3.         $("#btnSearch").click(function () {
  4.             
  5.         });
  6.     });
  7. </script>

now comes the clever bit, we need to use Jquery’s getJSON method to request the location information from the Bing Maps REST API for the address the user has entered. The getJSON method is pretty simple and has the following signature:

jQuery.getJSON( url, [ data ], [ callback(data, textStatus) ] )

url - A string containing the URL to which the request is sent.

data - A map or string that is sent to the server with the request.

callback(data, textStatus) - A callback function that is executed if the request succeeds.

So the code to call the Bing Maps REST API to query the location of an non-structured address using the following url

https://dev.virtualearth.net/REST/v1/Locations/query?key=BingMapsKey

You’ll notice you will need to put your own Bing Maps key into the url which you can get from https://www.bingmapsportal.com/. Here is the code we need to make the call in Jquery.


  1. $(document).ready(function () {
  2.     $("#btnSearch").click(function () {
  3.         //check user has entered something first
  4.         if ($("#txtAddress").val().length > 0) {
  5.             //send location query to bing maps REST api
  6.             $.getJSON('https://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=YOURBINGMAPSKEY&jsonp=?', function(result) {
  7.                 alert("got a result");
  8.             });
  9.         }
  10.         else {
  11.             $("#results").html("please enter an address");
  12.         }
  13.     });
  14. });

 

The important parts to notice are how we construct the call to Jquery’s getJSON method. The first parameter to the call is the url to load json data from, in this case we are building the url string up to include the value the user has entered in the textbox.

The critical part of this url is the addition of the “&jsonp=?” to the end of the url, this allow jquery to create a proxy allowing your code to make a cross domain call to a different url than the one the page is running on. Without this javascript would not be able to make the call to the Bing Maps REST API. The “?” is where jquery does its magic and behind the scenes wires up your success callback code (the second parameter) and the callback that is sent to the Bing Maps REST API.

As we just mentioned the second parameter is the function you want to be called when the result successfully comes back.For now this code will just show an message box but now to actually read in the data.

Reading the data returned

The data returned by the location service is quite complex and its easier to explore using a tool like firebug (the firefox plugin) or IE or chromes built in javascript debuggers. Here is a screen shot of what the data looks like returned from this call.

bingmapsreturned

As you can see you may get more than one “resources” object back if your address could match more than one place in the world. In this example we will just use the first result returned, but in real life you would want to present the user with a list of the possible options to choose from.

So the last bit of code to check if we have a result, and then write out the latitude and longitude of the location is as follows.

  1. $(document).ready(function () {
  2.     $("#btnSearch").click(function () {
  3.         //check user has entered something first
  4.         if ($("#txtAddress").val().length > 0) {
  5.             //send location query to bing maps REST api
  6.             $.getJSON('https://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=YOURBINGMAPSKEY&jsonp=?', function (result) {
  7.                 if (result.resourceSets[0].estimatedTotal > 0) {
  8.                     var loc = result.resourceSets[0].resources[0].point.coordinates;
  9.                     $("#results").html('latitude:' + loc[0] + ', longitude:' + loc[1]);
  10.                 }
  11.                 else {
  12.                     $("#results").html("sorry that address cannot be found");
  13.                 }
  14.             });
  15.         }
  16.         else {
  17.             $("#results").html("please enter an address");
  18.         }
  19.     });
  20. });

Summary

This simple example has hopefully shown you just how easy it is to call the Bing Maps REST webservices using Jquery, and just how little code is required for a completely cross browser solution.

To try it out for yourself, download the code using the link below and add your own bing maps key

.butdownloadcode[1]

Close chatbot
Open chatbot
Open chatbot