开发者

Find nearby entities with Bing Maps REST control

I'm attempting to use the Bing Maps REST API to query the addresses of all entities, of a given name, within a given search radius. The end goal is to do something like what Starbucks does here: Store Locator, but I used Fiddler and it looks like they are using the 6.3 API :/

This seems very poorly documented if there is a way to do this. There are some examples of how to do this if you upload your own data, but not if you're searching for local businesses that should already be on the map: Examples. Here's what I have tried so far...it is returning Starbucks, Oregon:

var query = 'starbucks';
_map.getCredentials(function (credentials) {
    $.getJSON('http://dev.virtualearth.net/REST/V1/Locations/' + query + '?key=' + credentials + '&lat=' + position.coords.latitude + '&long=' + position.coords.longitude + '&limit=25&jsonp=?&s=1',
    function (result) {
        if (result.resourceSets[0].address != 'undefined') {
            var address = result.resourceSets[0].address;
            alert(address);
        }
        else {
            $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
        }
    });
});

This is the code that precedes the location query in case you're wondering what the location data is that I'm using in the location query - it's essentially from the user's location via the geolocation API:

var _map;

$(document).ready(function () {
    if (Modernizr.geolocation) {
        $(".geofallback").hide();
    }
    else {
        $(".geofallback").show();
    }
    $.post("Home/Key", { "func": "Key" }, function (data) {
        // Create a Bing map
        _map = new Microsoft.Maps.Map(document.getElementById("map"),
            { credentials: data, mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey });
    });
    // Get the current position from the browser
    if (!navigator.geolocation) {
        $("#results").html("This browser doesn't support geolocation, please enter an address");
    }
    else {
        navigator.geolocation.getCurrentPosition(onPositionReady, onError);
    }
});

function onPositi开发者_运维知识库onReady(position) {

    // Apply the position to the map
    var location = new Microsoft.Maps.Location(position.coords.latitude,
            position.coords.longitude);
    _map.setView({ zoom: 18, center: location });

    // Add a pushpin to the map representing the current location
    var pin = new Microsoft.Maps.Pushpin(location);
    _map.entities.push(pin); 
var query = 'starbucks';
    _map.getCredentials(function (credentials) {
        $.getJSON('http://dev.virtualearth.net/REST/V1/Locations/' + query + '?key=' + credentials + '&lat=' + position.coords.latitude + '&long=' + position.coords.longitude + '&limit=25&jsonp=?&s=1',
        function (result) {
            if (result.resourceSets[0].address != 'undefined') {
                var address = result.resourceSets[0].address;
                alert(address);
            }
            else {
                $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
            }
        });
    });
}

Any help would be greatly appreciated!!


The Bing Maps Locations API is for geocoding - i.e. finding addresses or places on the map. What you want to do is find things and then place them on the map. For this, you need to use the Bing API (not the Bing Maps API).

The Bing Phonebook search REST service should give you what you need - there's an example here: http://msdn.microsoft.com/en-us/library/dd251030.aspx Each result from the phonebook search has a Latitude and Longitude property which you can use to create a pushpin on the map.


Thank you Alastair - worked perfectly! Below is a working example of the code most of which has slightly adapted from the Microsoft code that Alastair linked me to: http://msdn.microsoft.com/en-us/library/dd251030.aspx .

This is in the context of MVC3 using the Bing Maps API in conjunction with the Bing Address Book API so the other code is for adjusting the map to the user's geolocation then this is used to find the nearest x number (maximum of 25 results per search) of whatever you're looking for - in this case, coffee!!

$.post("Home/GetBingMapsKey", ... and $.post("Home/GetBingKey", ... are in the context of an ASP.NET MVC3 Controller that simply returns the key...not that it makes the key secure since there is unfortunately no way to pass the key in the headers using the REST API...

var _map;
var _appId;

$(document).ready(function () {
    if (Modernizr.geolocation) {
        $(".geofallback").hide();
    }
    else {
        $(".geofallback").show();
    }
    $.post("Home/GetBingMapsKey", { "func": "GetBingMapsKey" }, function (data) {
        // Create a Bing map
        _map = new Microsoft.Maps.Map(document.getElementById("map"),
            { credentials: data }); //, mapTypeId: Microsoft.Maps.MapTypeId.ordnanceSurvey
    });
    $.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
        _appId = data;
    });
    // Get the current position from the browser
    if (!navigator.geolocation) {
        $("#results").html("This browser doesn't support geolocation, please enter an address");
    }
    else {
        navigator.geolocation.getCurrentPosition(onPositionReady, onError);
        navigator.geolocation.getCurrentPosition(Search, onError);
    }
});

function onPositionReady(position) {

    // Apply the position to the map
    var location = new Microsoft.Maps.Location(position.coords.latitude,
            position.coords.longitude);
    _map.setView({ zoom: 18, center: location });

    // Add a pushpin to the map representing the current location
    var pin = new Microsoft.Maps.Pushpin(location);
    _map.entities.push(pin);
}

function onError(err) {
    switch (err.code) {
        case 0:
            alert("Unknown error :(");
            break;
        case 1:
            alert("Location services are unavailable per your request.");
            break;
        case 2:
            alert("Location data is unavailable.");
            break;
        case 3:
            alert("The location request has timed out. Please contact support if you continue to experience issues.");
            break;
    }
}

function Search(position) {

    var requestStr = "http://api.bing.net/json.aspx?"

        // Common request fields (required)
        + "AppId=" + _appId
        + "&Query=starbucks"
        + "&Sources=Phonebook"

        // Common request fields (optional)
        + "&Version=2.2"
        + "&Market=en-us"
        + "&UILanguage=en"
        + "&Latitude=" + position.coords.latitude
        + "&Longitude=" + position.coords.longitude
        + "&Radius=100.0"
        + "&Options=EnableHighlighting"

        // Phonebook-specific request fields (optional)

        // Phonebook.Count max val is 25
        + "&Phonebook.Count=25"
        + "&Phonebook.Offset=0"
        // YP = Commercial Entity, WP = Residential
        + "&Phonebook.FileType=YP"
        + "&Phonebook.SortBy=Distance"

        // JSON-specific request fields (optional)
        + "&JsonType=callback"
        + "&JsonCallback=?";

    $.getJSON(requestStr, function (data) {
        SearchCompleted(data);
    });
    //var requestScript = document.getElementById("searchCallback");
    //requestScript.src = requestStr;
}

function SearchCompleted(response) {
    var errors = response.SearchResponse.Errors;
    if (errors != null) {
        // There are errors in the response. Display error details.
        DisplayErrors(errors);
    }
    else {
        // There were no errors in the response. Display the
        // Phonebook results.
        DisplayResults(response);
    }
}

function DisplayResults(response) {
    var output = document.getElementById("output");
    var resultsHeader = document.createElement("h4");
    var resultsList = document.createElement("ul");
    output.appendChild(resultsHeader);
    output.appendChild(resultsList);

    var results = response.SearchResponse.Phonebook.Results;

    // Display the results header.
    resultsHeader.innerHTML = "Bing API Version "
            + response.SearchResponse.Version
            + "<br />Phonebook results for "
            + response.SearchResponse.Query.SearchTerms
            + "<br />Displaying "
            + (response.SearchResponse.Phonebook.Offset + 1)
            + " to "
            + (response.SearchResponse.Phonebook.Offset + results.length)
            + " of "
            + response.SearchResponse.Phonebook.Total
            + " results<br />";

    // Display the Phonebook results.
    var resultsListItem = null;
    var resultStr = "";
    for (var i = 0; i < results.length; ++i) {
        resultsListItem = document.createElement("li");
        resultsList.appendChild(resultsListItem);
        resultStr = results[i].Business
                + "<br />"
                + results[i].Address
                + "<br />"
                + results[i].City
                + ", "
                + results[i].StateOrProvince
                + "<br />"
                + results[i].PhoneNumber
                + "<br />Average Rating: "
                + results[i].UserRating
                + "<br /><br />";

        // Replace highlighting characters with strong tags.
        resultsListItem.innerHTML = ReplaceHighlightingCharacters(
                resultStr,
                "<strong>",
                "</strong>");
    }
}

function ReplaceHighlightingCharacters(text, beginStr, endStr) {
    // Replace all occurrences of U+E000 (begin highlighting) with
    // beginStr. Replace all occurrences of U+E001 (end highlighting)
    // with endStr.
    var regexBegin = new RegExp("\uE000", "g");
    var regexEnd = new RegExp("\uE001", "g");

    return text.replace(regexBegin, beginStr).replace(regexEnd, endStr);
}

function DisplayErrors(errors) {
    var output = document.getElementById("output");
    var errorsHeader = document.createElement("h4");
    var errorsList = document.createElement("ul");
    output.appendChild(errorsHeader);
    output.appendChild(errorsList);

    // Iterate over the list of errors and display error details.
    errorsHeader.innerHTML = "Errors:";
    var errorsListItem = null;
    for (var i = 0; i < errors.length; ++i) {
        errorsListItem = document.createElement("li");
        errorsList.appendChild(errorsListItem);
        errorsListItem.innerHTML = "";
        for (var errorDetail in errors[i]) {
            errorsListItem.innerHTML += errorDetail
                    + ": "
                    + errors[i][errorDetail]
                    + "<br />";
        }

        errorsListItem.innerHTML += "<br />";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜