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



我正在尝试使用Bing Maps REST API来查询给定名称下给定搜索半径内所有实体的地址。最终目标是做一些类似星巴克在这里做的事情:商店定位器,但我使用的是Fiddler,看起来他们正在使用6.3 API:/

如果有办法做到这一点,这似乎是非常糟糕的文档。如果你上传自己的数据,有一些例子可以说明如何做到这一点,但如果你正在搜索应该已经在地图上的本地企业,就不需要这样做:例子。以下是我到目前为止所做的尝试……星巴克,俄勒冈:

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. :( ");
        }
    });
});

这是位置查询之前的代码,如果你想知道我在位置查询中使用的位置数据是什么-它本质上是从用户的位置通过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 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. :( ");
            }
        });
    });
}

任何帮助将非常感激!!

必应地图位置API用于地理编码-即在地图上查找地址或地点。你要做的是找到的东西,然后把它们放在地图上。为此,您需要使用必应API(而不是必应地图API)。

Bing电话簿搜索REST服务应该能满足你的需求——这里有一个例子:http://msdn.microsoft.com/en-us/library/dd251030.aspx来自电话簿搜索的每个结果都有一个Latitude和Longitude属性,您可以使用该属性在地图上创建图钉。

谢谢Alastair -工作完美!下面是代码的工作示例,其中大部分代码略微改编自Alastair链接给我的微软代码:http://msdn.microsoft.com/en-us/library/dd251030.aspx。

这是在MVC3使用Bing地图API与Bing地址簿API的背景下,所以其他代码是用于调整地图到用户的地理位置,然后这是用来找到最近的x数字(每次搜索最多25个结果),无论你在寻找什么-在这种情况下,咖啡!!

$。文章("Home/GetBingMapsKey",…和美元。文章("Home/GetBingKey",…都在ASP的上下文中。. NET mvc控制器,简单地返回键…并不是说它使密钥安全,因为不幸的是没有办法使用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 />";
    }
}

最新更新