【问题标题】:Find nearby entities with Bing Maps REST control使用 Bing 地图 REST 控件查找附近的实体
【发布时间】:2011-09-30 17:16:44
【问题描述】:

我正在尝试使用 Bing 地图 REST API 来查询给定搜索半径内所有实体的地址,给定名称。最终目标是像星巴克在这里所做的那样:Store Locator,但我使用了 Fiddler,看起来他们使用的是 6.3 API:/

如果有办法做到这一点,这似乎记录得很差。如果您上传自己的数据,有一些示例说明如何执行此操作,但如果您正在搜索应该已经在地图上的本地企业:Examples。到目前为止,这是我尝试过的......它正在返回俄勒冈州的星巴克:

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

任何帮助将不胜感激!

【问题讨论】:

    标签: jquery asp.net ajax geolocation bing-maps


    【解决方案1】:

    感谢 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 />";
        }
    }
    

    【讨论】:

      【解决方案2】:

      Bing Maps Locations API 用于地理编码 - 即在地图上查找地址或地点。您要做的是找到事物,然后将它们放在地图上。为此,您需要使用 Bing API(而不是 Bing Maps API)。

      必应电话簿搜索 REST 服务应该可以满足您的需求 - 这里有一个示例:http://msdn.microsoft.com/en-us/library/dd251030.aspx 电话簿搜索的每个结果都有一个纬度和经度属性,您可以使用它在地图上创建图钉。

      【讨论】:

      • 谢谢阿拉斯泰尔!我会试一试。如果这项工作一如既往,我一定会确认这是公认的答案并发布工作代码示例。
      • 请注意:电话簿 REST 服务不包括营业时间和企业网站 Url。但是,Bing 地图搜索 SOAP 服务确实包含您需要的数据。出于某种原因,必应地图搜索 API 不提供 REST 接口(奇怪的是,所有其他服务都提供)。
      • 只是给现在正在查看此内容的任何人的说明:此内容已不存在。
      猜你喜欢
      • 2011-06-04
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多