使用Bing Maps REST控件查找附近实体

4
我正在尝试使用Bing Maps REST API查询给定搜索半径内具有特定名称的所有实体的地址。最终目标是像星巴克在这里Store Locator所做的那样,但我使用了Fiddler,看起来他们正在使用6.3 API :/
如果有方法可以做到这一点,这似乎文档非常不完善。如果您上传自己的数据,则有一些如何执行此操作的示例,但如果您正在搜索应已在地图上的本地企业,则没有这些示例:Examples。到目前为止,这是我尝试过的...它返回的是Starbucks,俄勒冈州的结果。
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. :( ");
        }
    });
});

这是在位置查询之前的代码,以防你想知道我在位置查询中使用的位置数据 - 它基本上来自用户的位置通过地理位置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 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); 
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. :( ");
            }
        });
    });
}

任何帮助都将不胜感激!!
2个回答

5
Bing Maps Locations API 是用于地理编码的,即在地图上查找地址或地点。您想做的是查找“事物”,然后将它们放在地图上。为此,您需要使用 Bing API(而不是 Bing Maps API)。
Bing Phonebook 搜索 REST 服务应该可以为您提供所需的信息 - 这里有一个示例:http://msdn.microsoft.com/en-us/library/dd251030.aspx。每个电话簿搜索结果都有纬度和经度属性,您可以使用这些属性在地图上创建标注。

谢谢Alastair!我会试一下。如果这个方法有效,我会确认这是被接受的答案,并发布一个可行的代码示例。 - Jordan
请注意:电话簿 REST 服务不包括营业时间和商家网站 URL。然而,如果您需要这些数据,Bing Maps 搜索 SOAP 服务则包含它们。出于某种原因,Bing Maps 搜索 API 不提供 REST 接口(奇怪的是,所有其他服务都提供)。 - Rebecca
只是一个提醒,如果现在有人看这个内容:它已经不存在了。 - Seiyria
链接无法使用(虽然解决方案中不允许链接?)将尝试使用archiveit/waybackinternet... - JB-007
没事,我看到它已经在上面复制了! :) - JB-007
请仅返回翻译后的文本: https://web.archive.org/web/20120419154522/http://msdn.microsoft.com/en-us/library/dd251030.aspx(为了完整起见) - JB-007

0

谢谢Alastair - 完美地工作了!以下是一个可行的代码示例,其中大部分代码都是从Alastair链接给我的Microsoft代码中稍加修改而来:http://msdn.microsoft.com/en-us/library/dd251030.aspx

这是在MVC3的上下文中使用Bing Maps API与Bing Address Book API结合使用,因此其他代码用于调整地图到用户的地理位置,然后将其用于查找最近的x个(每次搜索最多25个结果)任何你想要的东西 - 在这种情况下,是咖啡!

$.post("Home/GetBingMapsKey", ... 和 $.post("Home/GetBingKey", ... 是在ASP.NET MVC3控制器的上下文中,它只是返回密钥...不过这并不使密钥安全,因为不幸的是没有办法通过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 />";
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接