在 bing 地图 API 中使用 currentLocation 以及企业搜索

发布于 2024-11-19 08:06:57 字数 334 浏览 3 评论 0原文

我目前在此网站,该网站展示了如何使用必应地图 API。但我想要实现的是,首先地图应该获取您当前的位置并搜索附近的业务类型,比如说餐厅或支票兑现地点。 我的当前页面具有当前位置,但现在我如何在我的页面上实现 FindNearBy 函数?

PS 我希望用户无需输入搜索文本即可进行搜索,因此地图应加载当前位置,并且其旁边应列出附近所有或最近的 5 家餐厅。

I was currently at this site which shows how to implement business search using the bing map api. But what I am trying to implement is, first the map should get your current location and search for type of business nearby, let's say Restaurant or Check Cashing place.
My current page has the current location working but now how I implement the FindNearBy function with my page?

P.s. I want the search to already take place for the user without having to enter a search text, so the map should load up with current location and right next to it should list all or maybe the closest 5 restaurant nearby.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女情怀诗 2024-11-26 08:06:57

不适用于 Bing 地图...您需要 Bing 电话簿 API 来执行此操作。

我可以带你去那里。下面的示例结合了 Bing 地图 API 和 Bing 电话簿 API 的使用)我刚刚提交了一个关于如何查找业务类型的类似问题,但是...我不确定是否有办法做到这一点:/ (下面的示例搜索该地区的所有星巴克...当然,需要一些 HTML 集成。

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
    });

    // Get the current position from the browser
    if (!navigator.geolocation) {
        $("#results").html("This browser doesn't support geolocation, please enter an address");
    }
else {
        $.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
            _appId = data;
        });
        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) {
          // note a bunch of this code uses the example code from
          // Microsoft for the Phonebook API
    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);
    });
}

function FormatBingQuery(appId, latitude ) {
}

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);
                    //loc is specific to my C# object
        var loc = new Array();
        loc[0] = results[i].Longitude;
        loc[1] = results[i].Latitude;

        var address = {
            AddressLine1: results[i].Address,
            City: results[i].City,
            State: results[i].StateOrProvince,
            PostalCode: results[i].PostalCode,
            Latitude: results[i].Latitude,
            Longitude: results[i].Longitude,
            Country: results[i].CountryOrRegion,
            ID: results[i].UniqueId
        };
                    //this part is specific to my project to return the 
                    //address results so I can store them (since my
                    //implementation is a demonstration of how to 
                    //use the MongoDB geoNear() functionality
        $.ajax({
            url: "/Home/AddAddressToCollection",
            type: 'post',
            data: JSON.stringify(address),
            contentType: 'application/json',
            dataType: 'json'
        });

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

    // Bonus: In case you want to provide directions
    // for how to get to a selected entity

    //            _map.getCredentials(function (credentials) {
    //                $.getJSON('http://dev.virtualearth.net/REST/V1/Routes/driving?' + 'wp.0=' + lat1 + ',' + lon1 + '&wp.1=' + lat2 + ',' + lon2 + '&distanceUnit=mi&optmz=distance&key=' + credentials + '&jsonp=?&s=1',
    //                function (result) {
    //                    if (result.resourceSets[0].estimatedTotal > 0) {
    //                        var distance = result.resourceSets[0].resources[0].travelDistance;
    //                    }
    //                    else {
    //                        $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
    //                    }
    //                });
    //            });

//Tie into a function that shows an input field
//for use as a fallback in case cannot use HTML5 geoLocation
//$(document).ready(function () {
//    $("#btnFindLocation").click(function () {
//        //check user has entered something first
//        if ($("#txtAddress").val().length > 0) {
//            //send location query to bing maps REST api
//            _map.getCredentials(function (credentials) {
//                $.getJSON('http://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=' + credentials + '&jsonp=?&s=1', 
//                    function (result) {
//                        if (result.resourceSets[0].estimatedTotal > 0) {
//                            var loc = result.resourceSets[0].resources[0].point.coordinates;
//                            $("#lat").val(loc[0]);
//                            $("#lon").val(loc[1]);
//                            var location = new Microsoft.Maps.Location(loc[0],
//                                loc[1]);
//                            _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);
//                        }
//                        else {
//                            $("#results").html("sorry that address cannot be found");
//                        }
//                });
//            });
//        }
//        else {
//            $("#results").html("please enter an address");
//        }
//    });
//});

Not with Bing Maps...you need the Bing Phonebook API to do this.

I can get you part of the way there. The below example combines the use of both the Bing Maps API and the Bing Phonebook API) I just submitted a similar question about how to find the type of business, however...I'm not sure there's a wayto do this :/ (Below example searches for all Starbucks in the area ...of course, some HTML integration is required.

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
    });

    // Get the current position from the browser
    if (!navigator.geolocation) {
        $("#results").html("This browser doesn't support geolocation, please enter an address");
    }
else {
        $.post("Home/GetBingKey", { "func": "GetBingKey" }, function (data) {
            _appId = data;
        });
        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) {
          // note a bunch of this code uses the example code from
          // Microsoft for the Phonebook API
    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);
    });
}

function FormatBingQuery(appId, latitude ) {
}

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);
                    //loc is specific to my C# object
        var loc = new Array();
        loc[0] = results[i].Longitude;
        loc[1] = results[i].Latitude;

        var address = {
            AddressLine1: results[i].Address,
            City: results[i].City,
            State: results[i].StateOrProvince,
            PostalCode: results[i].PostalCode,
            Latitude: results[i].Latitude,
            Longitude: results[i].Longitude,
            Country: results[i].CountryOrRegion,
            ID: results[i].UniqueId
        };
                    //this part is specific to my project to return the 
                    //address results so I can store them (since my
                    //implementation is a demonstration of how to 
                    //use the MongoDB geoNear() functionality
        $.ajax({
            url: "/Home/AddAddressToCollection",
            type: 'post',
            data: JSON.stringify(address),
            contentType: 'application/json',
            dataType: 'json'
        });

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

    // Bonus: In case you want to provide directions
    // for how to get to a selected entity

    //            _map.getCredentials(function (credentials) {
    //                $.getJSON('http://dev.virtualearth.net/REST/V1/Routes/driving?' + 'wp.0=' + lat1 + ',' + lon1 + '&wp.1=' + lat2 + ',' + lon2 + '&distanceUnit=mi&optmz=distance&key=' + credentials + '&jsonp=?&s=1',
    //                function (result) {
    //                    if (result.resourceSets[0].estimatedTotal > 0) {
    //                        var distance = result.resourceSets[0].resources[0].travelDistance;
    //                    }
    //                    else {
    //                        $("#results").html("Oops! It appears one or more of the addresses you entered are incorrect. :( ");
    //                    }
    //                });
    //            });

//Tie into a function that shows an input field
//for use as a fallback in case cannot use HTML5 geoLocation
//$(document).ready(function () {
//    $("#btnFindLocation").click(function () {
//        //check user has entered something first
//        if ($("#txtAddress").val().length > 0) {
//            //send location query to bing maps REST api
//            _map.getCredentials(function (credentials) {
//                $.getJSON('http://dev.virtualearth.net/REST/v1/Locations?query=' + $("#txtAddress").val() + '&key=' + credentials + '&jsonp=?&s=1', 
//                    function (result) {
//                        if (result.resourceSets[0].estimatedTotal > 0) {
//                            var loc = result.resourceSets[0].resources[0].point.coordinates;
//                            $("#lat").val(loc[0]);
//                            $("#lon").val(loc[1]);
//                            var location = new Microsoft.Maps.Location(loc[0],
//                                loc[1]);
//                            _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);
//                        }
//                        else {
//                            $("#results").html("sorry that address cannot be found");
//                        }
//                });
//            });
//        }
//        else {
//            $("#results").html("please enter an address");
//        }
//    });
//});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文