Categories
Bing Maps Microsoft

Use Bing Maps REST Services with jQuery to build an autocomplete box and find a location dynamically

In this article we will discover how to build an autocomplete box with Bing Maps REST Services by using only HTML, JSON and jQuery.

Bing Maps REST Services allows us to perform tasks such as creating a map with pushpins, geocoding an address, retrieving imagery metadata, or creating a route.

Here we will learn to use the Locations API of Bing Maps REST Services to build an autocomplete box with jQuery. To be able to reach Bing Maps services, you will need a Bing Maps key. Just go to the Bing Maps Account Center to get one.

 

Creation

First, we will create a simple HTML page with references to jQuery and jQuery UI, an input for the searched location and a div in which the results will be displayed.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Use Bing Maps REST Services with jQuery to build an autocomplete box and find a location dynamically</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        #searchBox
        {
            width: 25em;
        }
    </style>
</head>
<body>
    <div>
        <div class="ui-widget">
            <label for="searchBox">
                Search:
            </label>
            <input id="searchBox" />
        </div>
        <div id="searchResult" class="ui-widget" style="margin-top: 1em;">
        </div>
    </div>
</body>
</html>

 

To call the Locations API we use the following url: http://dev.virtualearth.net/REST/v1/Locations

Parameters are required to get a response from the service:

The Bing Maps REST Services also have other optional parameters such as:

  • userLocation (or ul): current position of the user.
  • culture (or c): culture to use for the request.
  • output (or o): output format for the response (JSON or XML). JSON is used by default.
  • jsonp: name of JSON callback function that is called when the response to the request is received. The JSON object provided in the response is passed to the callback function.

 

To create an autocomplete box, we use jQuery UI. The source of the suggestions provided to the user will come from Bing Maps REST Services.

The operation is as follows: when the user type a location, an Ajax request is triggered to call the Locations API of Bing Maps REST Services and a JSON response is received. The response is processed to be displayed as suggestions to the user. Here is the JavaScript to do it:

<script type="text/javascript">
    $(document).ready(function () {
        $("#searchBox").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "http://dev.virtualearth.net/REST/v1/Locations",
                    dataType: "jsonp",
                    data: {
                        key: "<yourbingmapskey>",
                        q: request.term
                    },
                    jsonp: "jsonp",
                    success: function (data) {
                        var result = data.resourceSets[0];
                        if (result) {
                            if (result.estimatedTotal > 0) {
                                response($.map(result.resources, function (item) {
                                    return {
                                        data: item,
                                        label: item.name + ' (' + item.address.countryRegion + ')',
                                        value: item.name
                                    }
                                }));
                            }
                        }
                    }
                });
            },
            minLength: 1
        });
    });
</script>

 

We have to pay attention to several things here:

  • We specify to jQuery that the source of the autocomplete is an Ajax request sent to the Locations API of Bing Maps REST Services. Once the request response received, the autocomplete get suggestions thanks to the callback named response.
  • Ajax request has multiple settings:
    • url: is the one for Locations API.
    • dataType: jsonp.
    • jsonp: is jsonp to override the callback function name in the jsonp request, so that jQuery add an extra “?jsonp=?” to the end of the URL to specify the callback. That is required by Bing Maps REST Services.
  • We get the searched term from request.term parameter.
  • We check that the Bing Maps REST Services response contains resource sets and if it has found locations that match searched term (result.estimatedTotal > 0). For more details about Bing Maps REST Services response see: Common Response Description on MSDN.
  • In the response callback, we specify that the suggestion label will be the location name plus the location country, and that the value will be the location name. We also use the property named data to save the full location information in order to use it when the user will the select a location.

 

For example, when a user search “San Francisco”, the following Ajax request url is built and called:

http://dev.virtualearth.net/REST/v1/Locations?jsonp=<callbackname>&key=<yourbingmapskey>&q=San+francisco&_=1298745707161

 

The final working page source looks like below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Use Bing Maps REST Services with jQuery to build an autocomplete box and find a location dynamically</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js" type="text/javascript"></script>
    <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .ui-autocomplete-loading
        {
            background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
        }
        #searchBox
        {
            width: 25em;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function () {
            $("#searchBox").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "http://dev.virtualearth.net/REST/v1/Locations",
                        dataType: "jsonp",
                        data: {
                            key: "<yourbingmapskey>",
                            q: request.term
                        },
                        jsonp: "jsonp",
                        success: function (data) {
                            var result = data.resourceSets[0];
                            if (result) {
                                if (result.estimatedTotal > 0) {
                                    response($.map(result.resources, function (item) {
                                        return {
                                            data: item,
                                            label: item.name + ' (' + item.address.countryRegion + ')',
                                            value: item.name
                                        }
                                    }));
                                }
                            }
                        }
                    });
                },
                minLength: 1,
                change: function (event, ui) {
                    if (!ui.item)
                        $("#searchBox").val('');
                },
                select: function (event, ui) {
                    displaySelectedItem(ui.item.data);
                }
            });
        });

        function displaySelectedItem(item) {
            $("#searchResult").empty().append('Result: ' + item.name).append(' (Latitude: ' + item.point.coordinates[0] + ' Longitude: ' + item.point.coordinates[1] + ')');
        }
    </script>
</head>
<body>
    <div>
        <div class="ui-widget">
            <label for="searchBox">
                Search:
            </label>
            <input id="searchBox" />
        </div>
        <div id="searchResult" class="ui-widget" style="margin-top: 1em;">
        </div>
    </div>
</body>
</html>

 

Demo video

Links

Several links that will help you to understand and go further on the subject:

 

Summary

We have seen how to use Bing Maps REST Services with jQuery, jQuery UI to build an autocomplete box and find a location dynamically. As we are using HTML, JSON and jQuery, this can be integrated with whatever technology you prefer.

If you want to go further, take a look at the links above to understand what you can do with Bing Maps REST Services. For example, we could display the selected location on a map with Bing Maps AJAX Control or Bing Maps Silverlight Control. This will certainly be the next subject of one of my future articles in addition to this one.

You can download the full sources here:

Download full sources

 

Please feel free to comment or contact me if you have any question about this article.