Export (0) Print
Expand All

Show Spatial Data Search Results on a Map

Bing

This article shows how to build a web page that uses Bing Spatial Data Services to search a data source for entries near a location and then displays the results on a map by using the Bing Maps AJAX Control, Version 7.0 (interactive map) or the Bing Maps REST Services (static map). The Bing Maps REST Services is used to geocode the specified location. The public FourthCoffeeSample data source is used as the sample data source in this example.

The complete web page is listed at the end of the article.

Setup

Get a Bing Maps Key

You need a Bing Maps Key to use the Bing Maps APIs. If you do not have a Bing Maps Key, see Getting a Bing Maps Key for instructions.

Create a basic web page

  1. Copy the following basic HTML content and save it as a file with an .htm extension.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
        <title>Search and Map</title>
    </head>
    <body>
    </body>
    </html>
    
    
  2. Add the following elements to the header section of your HTML page. These elements set the content type to UTF-8 which is recommended. The script elements setup the reference to the map control and your Bing Maps Key.

    Hh305205.Important(en-us,MSDN.10).gifImportant:
    Make sure you replace the placeholder text below with your Bing Maps Key.

        <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">
    
            // Replace the following string with the Bing Maps Key you received from the
            // Bing Maps Account Center http://www.bingmapsportal.com
            var BingMapsKey = "";
            var map = null;
        </script>
    
    
    

Add a function to submit REST requests

The Bing Maps REST Services and Bing Spatial Data Services use a Representational State Transfer (REST) interface that makes HTTP requests. Insert the following function within the second set of script tags in your HTML page. You will use this function to make REST URL requests.

        //Make a REST request for the Bing Map REST Services and Bing Spatial Data Services
        function MakeServiceRequest(request) {
            var script = document.createElement("script");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", request);
            document.body.appendChild(script);
        }


Add body text and user input

Insert the following HTML in the body section of your HTML page. This HTML code includes input fields for the user to input a location and select a distance to use as “find nearby” search parameters. There are also DIV elements that will hold the results and display the interactive map.

    <div style="color:#330000;font-size:larger;font-family:Arial,Sans-Serif">
        <p> Search and Map FourthCoffeeShops Near a Location </p>
    </div>
    <div style="color:#003366;font-size:large"><span>Search within&nbsp;</span>
        <select id="distance">
            <option value="1">1</option>
            <option value="5">5</option>
            <option value="10" selected="selected">10</option>
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="200">200</option>  
            <option value="400">400</option>
        </select><span>&nbsp;kilometers of&nbsp;</span>
        <input id="address" type="text" value="Insert Location/Address" size="30" />  
        <input type="button" value="Search" onclick="Geocode()" />
    </div>
    <div>
        <div id="mapDiv" style="padding-top:10px;"></div> 
        <div id="output" ></div>
    </div>

Geocode the location using the REST Services

Insert the following functions after the MakeServiceRequest function. When the user inputs a location, the Bing Maps REST Services Locations API is used to geocode the result. The Geocode function builds the URL request that returns a JSON response and defines the JSON callback function. When the JSON response is received, it is passed to the JSON callback function named GetLocationCoordinates. The GetLocationCoordinates function retrieves the geocoded latitude and longitude from the response and passes these coordinates to the Search function defined in the next section.

        //Geocode the location specified by the user
        function Geocode() {
            //Create Bing Maps REST Services request to geocode the address provided by the user
            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
               + document.getElementById('address').value
               + "?output=json"
               //Set the callback function
               + "&jsonp=GetLocationCoordinates"
               + "&key=" + BingMapsKey;
            //Submit the request
            MakeServiceRequest(geocodeRequest);
        }

        //Get the geocoded latitude and longitude from the response
        function GetLocationCoordinates(geocodeResponse) {
            if (geocodeResponse &&
                   geocodeResponse.resourceSets &&
                   geocodeResponse.resourceSets.length > 0 &&
                   geocodeResponse.resourceSets[0].resources &&
                   geocodeResponse.resourceSets[0].resources.length > 0) {

                Search(geocodeResponse.resourceSets[0].resources[0].point.coordinates[0], geocodeResponse.resourceSets[0].resources[0].point.coordinates[1]);

            }
            else {//The location could not be geocoded
                document.getElementById("output").innerHTML = "";
                var output = document.getElementById("output");
                var resultsHeader = document.createElement("h4");
                output.appendChild(resultsHeader);
                resultsHeader.innerHTML = "The location could not be geocoded";
            }
        }

Search for nearby coffee shops using the Spatial Data Services

Insert the following function below the GetLocationCoordinates function. This Search function searches the FourthCoffeeShopes data source for shops near the geocoded latitude and longitude values and then uses the JSON callback functionality to pass the results to the MapResults function defined in the next section. A Query by Area URL request is used to perform the search. This URL is part of the Bing Spatial Data Services Query API.

        // Search the Fourth Coffee Shops data source for entities within "distance" 
        //of the geocoded location ("lat","long").
        function Search(lat, long) {

            //Get the distance to search selected by the user
            var distance = document.getElementById('distance').value;
            //Create a Bing Spatial Data Services request to search for entities and return the 
            var requestStr = 
"http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffeeSample/FourthCoffeeShops?"
            + "spatialFilter=nearby(" + lat + "," + long + "," + distance + ")"
            + "&
$select=EntityID,AddressLine,PrimaryCity,Subdivision,PostalCode,Latitude,Longitude&$top=10"
            + "&$format=json"
            + "&key=" + BingMapsKey
            // set the JSON callback function
            + "&Jsonp=MapResults";

            //Submit request
            MakeServiceRequest(requestStr);
        }

Show the search results on an interactive map

Insert the following MapResults function after the Search function. The MapResults function displays the address information for the search results and displays the locations on an Bing Maps AJAX Control 7.0 interactive map.

        //Show results (up to 10) and put them on the map
        function MapResults(response) {
            //Display list of results
            document.getElementById("output").innerHTML = "";
            var output = document.getElementById("output");
            var resultsHeader = document.createElement("h4");
            var resultsList = document.createElement("ol");
            output.appendChild(resultsHeader);
            output.appendChild(resultsList); 
            
            //Create pushpin collection to display on the map
            var pushpins = new Microsoft.Maps.EntityCollection();

            //Check if there are results
            if (response.d.results.length != 0) {
                //Get the search results
                var results = response.d.results;

                //initialize bounds for map area 
                var minLatitude = results[0].Latitude; var maxLatitude = results[0].Latitude; ;
                var minLongitude = results[0].Longitude; var maxLongitude = results[0].Longitude; 


                // Display results header
                resultsHeader.innerHTML = "Fourth Coffee Shops near your location"
                var resultsListItem = null;
                var resultStr = "";


                //Display each entity and create a pushpin for the map
                for (var i = 0; i < results.length; ++i) {
                    resultsListItem = document.createElement("li");
                    resultsList.appendChild(resultsListItem);
                    resultStr = "Store " + results[i].EntityID + "<br/>"
                        + results[i].AddressLine + "<br/>"
                        + results[i].PrimaryCity + ", "
                        + results[i].Subdivision + " "
                        + results[i].PostalCode + "<br/><br/>";
                    resultsListItem.innerHTML = resultStr;

                    // Add pushpin to map collection
                    var pushpinVal = (i+1).toString();
                    pushpins.push(new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(results
[i].Latitude, results[i].Longitude), { text: pushpinVal}));

                    //Determine bounds that display all pushpins
                    if (results[i].Latitude > maxLatitude) 
                    {maxLatitude = results[i].Latitude; }
                    else if (results[i].Latitude < minLatitude)
                    { minLatitude = results[i].Latitude; }

                    if (results[i].Longitude > maxLongitude)
                    { maxLongitude = results[i].Longitude; }
                    else if (results[i].Longitude < minLongitude)
                    { minLongitude = results[i].Longitude; }
                }

                //Create map using the AJAX 7 map control
                mapDiv.style.visibility = "visible";
                if (map != null) {map.dispose() };
                map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: 
BingMapsKey, height: 400, width: 400, mapTypeId: "r" });

                //Add the entity pushpins to the map
                map.entities.push(pushpins);

                //Add padding to map area so that pushpins are not on the edge
                minLatitude -= 0.0001;
                maxLatitude += 0.0001;
                minLongitude -= 0.0001;
                maxLongitude += 0.0001;
                var mapArea = Microsoft.Maps.LocationRect.fromLocations(new 
Microsoft.Maps.Location(minLatitude,minLongitude),new Microsoft.Maps.Location
(maxLatitude,maxLongitude));
                map.setView({ bounds: mapArea });
            }
            else { //No results were returned
                resultsHeader.innerHTML = "No locations were found. Please try another location or 
increase the search distance."
                resultsHeader.style.color = "DarkRed";
                resultsHeader.style.fontFamily = "sans-serif";
                resultsHeader.style.fontWeight = "normal";
                map.dispose();
            }

        }

View in browser

You have now created a web application. Save your file and view it in a browser such as Internet Explorer. Some browsers, such as Internet Explorer 9, may require you to allow the use of scripts on the page. Make sure to insert your Bing Maps Key and before viewing.

Alternative: Show the results on a static map

If you prefer to show the search results on a static map, replace the MapResults function above with the following StaticMapResults function and change the JSON Callback function for the Bing Spatial Data Services from MapResults to StaticMapResults. The StaticMapResults function uses a Get a Static Map REST URL that is part of the Bing Maps REST Services Imagery API.

StaticMapResults function

             function StaticMapResults(response) {
            //Create list of results
            document.getElementById("output").innerHTML = "";
            var output = document.getElementById("output");
            var resultsHeader = document.createElement("h4");
            var resultsList = document.createElement("ol");
            output.appendChild(resultsHeader);
            output.appendChild(resultsList);

            //Create REST Static Image URL
            var mapURL = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road?mapVersion=v1&key=" + BingMapsKey;

            if (response.d.results.length != 0) {
                //Get the search results
                var results = response.d.results;

                //initialize bounds for map area
                var minLatitude = results[0].Latitude; var maxLatitude = results[0].Latitude; ;
                var minLongitude = results[0].Longitude; var maxLongitude = results[0].Longitude;

                // Display results header
                resultsHeader.innerHTML = "Fourth Coffee Shops near your location"
                var resultsListItem = null;
                var resultStr = "";

                // Display the results.
                var resultsListItem = null;
                var resultStr = "";


                //Display each entity and create a pushpin for the map
                for (var i = 0; i < results.length; ++i) {
                    resultsListItem = document.createElement("li");
                    resultsList.appendChild(resultsListItem);
                    resultStr = "Store " + results[i].EntityID + "<br/>"
                        + results[i].AddressLine + "<br/>"
                        + results[i].PrimaryCity + ", "
                        + results[i].Subdivision + " "
                        + results[i].PostalCode + "<br/><br/>";
                    resultsListItem.innerHTML = resultStr;


                    if (results[i].Latitude > maxLatitude)
                    { maxLatitude = results[i].Latitude; }
                    else if (results[i].Latitude < minLatitude)
                    { minLatitude = results[i].Latitude; }

                    if (results[i].Longitude > maxLongitude)
                    { maxLongitude = results[i].Longitude; }
                    else if (results[i].Longitude < minLongitude)
                    { minLongitude = results[i].Longitude; }

                    mapURL = mapURL + "&pp=" + results[i].Latitude.toString() + "," + results[i].Longitude.toString() + ";;" + (i + 1).toString();
                }

 
             minLatitude -= 0.0001;
             maxLatitude += 0.0001;
             minLongitude -= 0.0001;
             maxLongitude += 0.0001;

             mapURL = mapURL + "&mapArea=" + minLatitude.toString() + "," + minLongitude.toString() + ","
                                + maxLatitude.toString() + "," + maxLongitude.toString() 
                                + "&declutter=1";


                //Create img element to hold static map
                var map = document.createElement("img");
                map.setAttribute("alt","Static Map showing Fourth Coffee Shops");
                map.setAttribute("style", "padding-left: 10px");
                map.setAttribute("src", mapURL);
                document.getElementById("mapDiv").appendChild(map);
                }
            else { //No results were returned
                resultsHeader.innerHTML = "No locations were found. Please try another location or increase the search distance."
                resultsHeader.style.color = "DarkRed";
                resultsHeader.style.fontFamily = "sans-serif";
                resultsHeader.style.fontWeight = "normal";
                map.dispose();
            }

 }

Search function showing JSON Callback function name change

        // Search the Fourth Coffee Shops data source for entities within "distance" of the geocoded location ("lat","long").
        function Search(lat, long) {

            //Get the distance to search selected by the user
            var distance = document.getElementById('distance').value;
            //Create a Bing Spatial Data Services request to search for entities and return the first 10 results
            var requestStr = "http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffeeSample/FourthCoffeeShops?"
            + "spatialFilter=nearby(" + lat + "," + long + "," + distance + ")"
            + "&$select=EntityID,AddressLine,PrimaryCity,Subdivision,PostalCode,Latitude,Longitude&$top=10"
            + "&$format=json"
            + "&key=" + BingMapsKey
            // set the JSON callback function
            + "&Jsonp=StaticMapResults";

            //Submit request
            MakeServiceRequest(requestStr);
        }

Complete Sample

The following is the complete sample and displays an AJAX 7 interactive map. The code to display a static map is in comments. Make sure you insert your Bing Maps Key before running the sample.

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

        // Replace the following string with the Bing Maps Key you received from the
        // Bing Maps Account Center http://www.bingmapsportal.com

        var BingMapsKey = "INSERT_YOUR_BING_MAPS_KEY";
        var map = null;


        //Make a REST request for the Bing Map REST Services and Bing Spatial Data Services
        function MakeServiceRequest(request) {
            var script = document.createElement("script");
            script.setAttribute("type", "text/javascript");
            script.setAttribute("src", request);
            document.body.appendChild(script);
        }

        //Geocode the location specified by the user
        function Geocode() {
            //Create Bing Maps REST Services request to geocode the address provided by the user
            var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/"
               + document.getElementById('address').value
               + "?output=json"
               //Set the callback function
               + "&jsonp=GetLocationCoordinates"
               + "&key=" + BingMapsKey;
            //Submit the request
            MakeServiceRequest(geocodeRequest);
        }

        //Get the geocoded latitude and longitude from the response
        function GetLocationCoordinates(geocodeResponse) {
            if (geocodeResponse &&
                   geocodeResponse.resourceSets &&
                   geocodeResponse.resourceSets.length > 0 &&
                   geocodeResponse.resourceSets[0].resources &&
                   geocodeResponse.resourceSets[0].resources.length > 0) {

                Search(geocodeResponse.resourceSets[0].resources[0].point.coordinates[0], geocodeResponse.resourceSets[0].resources[0].point.coordinates[1]);

            }
            else {//The location could not be geocoded.
                document.getElementById("output").innerHTML = "";
                var output = document.getElementById("output");
                var resultsHeader = document.createElement("h4");
                output.appendChild(resultsHeader);
                resultsHeader.innerHTML = "The location could not be geocoded";
            }
        }

        // Search the Fourth Coffee Shops data source for entities within "distance" of the geocoded location ("lat","long").
        function Search(lat, long) {

            //Get the distance to search selected by the user
            var distance = document.getElementById('distance').value;
            //Create a Bing Spatial Data Services request to search for entities and return the
            var requestStr = "http://spatial.virtualearth.net/REST/v1/data/20181f26d9e94c81acdf9496133d4f23/FourthCoffeeSample/FourthCoffeeShops?"
            + "spatialFilter=nearby(" + lat + "," + long + "," + distance + ")"
            + "&$select=EntityID,AddressLine,PrimaryCity,Subdivision,PostalCode,Latitude,Longitude&$top=10"
            + "&$format=json"
            + "&key=" + BingMapsKey
            // set the JSON callback function
            + "&Jsonp=MapResults";
            // + "&Jsonp=StaticMapResults";

            //Submit reqquest
            MakeServiceRequest(requestStr);
        }


        //Show results (up to 10) and put them on the map
        function MapResults(response) {
            //Display list of results
            document.getElementById("output").innerHTML = "";
            var output = document.getElementById("output");
            var resultsHeader = document.createElement("h4");
            var resultsList = document.createElement("ol");
            output.appendChild(resultsHeader);
            output.appendChild(resultsList); 
            
            //Create pushpin collection to display on the map
            var pushpins = new Microsoft.Maps.EntityCollection();

            //Check if there are results
            if (response.d.results.length != 0) {
                //Get the search results
                var results = response.d.results;

                //initialize bounds for map area 
                var minLatitude = results[0].Latitude; var maxLatitude = results[0].Latitude; ;
                var minLongitude = results[0].Longitude; var maxLongitude = results[0].Longitude; 


                // Display results header
                resultsHeader.innerHTML = "Fourth Coffee Shops near your location"
                var resultsListItem = null;
                var resultStr = "";


                //Display each entity and create a pushpin for the map
                for (var i = 0; i < results.length; ++i) {
                    resultsListItem = document.createElement("li");
                    resultsList.appendChild(resultsListItem);
                    resultStr = "Store " + results[i].EntityID + "<br/>"
                        + results[i].AddressLine + "<br/>"
                        + results[i].PrimaryCity + ", "
                        + results[i].Subdivision + " "
                        + results[i].PostalCode + "<br/><br/>";
                    resultsListItem.innerHTML = resultStr;

                    // Add pushpin to map collection
                    var pushpinVal = (i+1).toString();
                    pushpins.push(new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(results[i].Latitude, results[i].Longitude), { text: pushpinVal}));

                    //Determine bounds that display all pushpins
                    if (results[i].Latitude > maxLatitude) 
                    {maxLatitude = results[i].Latitude; }
                    else if (results[i].Latitude < minLatitude)
                    { minLatitude = results[i].Latitude; }

                    if (results[i].Longitude > maxLongitude)
                    { maxLongitude = results[i].Longitude; }
                    else if (results[i].Longitude < minLongitude)
                    { minLongitude = results[i].Longitude; }
                }

                //Create map using the AJAX 7 map control
                mapDiv.style.visibility = "visible";
                if (map != null) {map.dispose() };
                map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), { credentials: BingMapsKey, height: 400, width: 400, mapTypeId: "r" });

                //Add the entity pushpins to the map
                map.entities.push(pushpins);

                //Add padding to map area so that pushpins are not on the edge
                minLatitude -= 0.0001;
                maxLatitude += 0.0001;
                minLongitude -= 0.0001;
                maxLongitude += 0.0001;
                var mapArea = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(minLatitude,minLongitude),new Microsoft.Maps.Location(maxLatitude,maxLongitude));
                map.setView({ bounds: mapArea });
            }
            else { //No results were returned
                resultsHeader.innerHTML = "No locations were found. Please try another location or increase the search distance."
                resultsHeader.style.color = "DarkRed";
                resultsHeader.style.fontFamily = "sans-serif";
                resultsHeader.style.fontWeight = "normal";
                map.dispose();
            }

        }


//             function StaticMapResults(response) {
//            //Create list of results
//            document.getElementById("output").innerHTML = "";
//            var output = document.getElementById("output");
//            var resultsHeader = document.createElement("h4");
//            var resultsList = document.createElement("ol");
//            output.appendChild(resultsHeader);
//            output.appendChild(resultsList);

//            //Create REST Static Image URL
//            var mapURL = "http://dev.virtualearth.net/REST/v1/Imagery/Map/Road?mapVersion=v1&key=" + BingMapsKey;

//            if (response.d.results.length != 0) {
//                //Get the search results
//                var results = response.d.results;

//                //initialize bounds for map area
//                var minLatitude = results[0].Latitude; var maxLatitude = results[0].Latitude; ;
//                var minLongitude = results[0].Longitude; var maxLongitude = results[0].Longitude;

//                // Display results header
//                resultsHeader.innerHTML = "Fourth Coffee Shops near your location"
//                var resultsListItem = null;
//                var resultStr = "";

//                // Display the results.
//                var resultsListItem = null;
//                var resultStr = "";


//                //Display each entity and create a pushpin for the map
//                for (var i = 0; i < results.length; ++i) {
//                    resultsListItem = document.createElement("li");
//                    resultsList.appendChild(resultsListItem);
//                    resultStr = "Store " + results[i].EntityID + "<br/>"
//                        + results[i].AddressLine + "<br/>"
//                        + results[i].PrimaryCity + ", "
//                        + results[i].Subdivision + " "
//                        + results[i].PostalCode + "<br/><br/>";
//                    resultsListItem.innerHTML = resultStr;


//                    if (results[i].Latitude > maxLatitude)
//                    { maxLatitude = results[i].Latitude; }
//                    else if (results[i].Latitude < minLatitude)
//                    { minLatitude = results[i].Latitude; }

//                    if (results[i].Longitude > maxLongitude)
//                    { maxLongitude = results[i].Longitude; }
//                    else if (results[i].Longitude < minLongitude)
//                    { minLongitude = results[i].Longitude; }

//                    mapURL = mapURL + "&pp=" + results[i].Latitude.toString() + "," + results[i].Longitude.toString() + ";;" + (i + 1).toString();
//                }

// 
//             minLatitude -= 0.0001;
//             maxLatitude += 0.0001;
//             minLongitude -= 0.0001;
//             maxLongitude += 0.0001;

//             mapURL = mapURL + "&mapArea=" + minLatitude.toString() + "," + minLongitude.toString() + ","
//                                + maxLatitude.toString() + "," + maxLongitude.toString() 
//                                + "&declutter=1";


//                //Create img element to hold static map
//                var map = document.createElement("img");
//                map.setAttribute("alt","Static Map showing Fourth Coffee Shops");
//                map.setAttribute("style", "padding-left: 10px");
//                map.setAttribute("src", mapURL);
//                document.getElementById("mapDiv").appendChild(map);
//                }
//            else { //No results were returned
//                resultsHeader.innerHTML = "No locations were found. Please try another location or increase the search distance."
//                resultsHeader.style.color = "DarkRed";
//                resultsHeader.style.fontFamily = "sans-serif";
//                resultsHeader.style.fontWeight = "normal";
//                map.dispose();
//            }

// }
    </script>
</head>
<body>
    <div style="color:#330000;font-size:larger;font-family:Arial,Sans-Serif">
        <p> Search and Map FourthCoffeeShops Near a Location </p>
    </div>
    <div style="color:#003366;font-size:large"><span>Search within&nbsp;</span>
        <select id="distance">
            <option value="1">1</option>
            <option value="5">5</option>
            <option value="10" selected="selected">10</option>
            <option value="25">25</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="200">200</option>  
            <option value="400">400</option>
        </select><span>&nbsp;kilometers of&nbsp;</span>
        <input id="address" type="text" value="Insert Location/Address" size="30" />  
        <input type="button" value="Search" onclick="Geocode()" />
    </div>
    <div>
        <div id="mapDiv" style="padding-top:10px;"></div> 
        <div id="output" ></div>
    </div>
</body>
</html>


Show:
© 2014 Microsoft