Skip to main content
 首页 » 编程设计

jquery之如何按用户位置过滤 Bing Location API 结果以实现自动完成

2026年07月28日5zhwl

我有这个函数根据用户输入的地址返回 bing 地址建议。 我已经指定了 userLocation,但结果并不像我想象的那么准确。我应该在这里做些什么额外的事情吗?如果需要,我可以手动指定州或邮政编码,但我宁愿避免进行后期处理。

例如,输入 111 将返回来自 111、NY、111 瑞典、111 丹麦的结果。我想至少将其限制在美国,并且实际上仅限于我可以硬编码的几个州。当我在数据中手动指定邮政编码选项时,它会覆盖我在查询中使用的选项。

    var geolocate = function(options) { 
    $.ajax({ 
        url: "http://dev.virtualearth.net/REST/v1/Locations", 
        dataType: "jsonp", 
        data: { 
            key: "KEY", 
            q: options.address, 
            userLocation: options.latitude + ',' + options.longitude, 
            maxResults: options.maxResults, 
        }, 
        jsonp: "jsonp", 
        success: function(data) { 
            if (options.success instanceof Function) { 
                options.success(data); 
            } 
        }, 
        error: function(xhr, status, text) { 
            alert('ERROR:\n'); 
        } 
    }); 
}; 

请您参考如下方法:

事实证明,这实际上会实现我的预期(除非测试证明不是这样),我将地址指定为单个参数 q,但如果我指定 addressLine 与 userLocation 结合使用,它会按预期过滤结果。

var geolocate = function(options) { 
    $.ajax({ 
        url: "http://dev.virtualearth.net/REST/v1/Locations", 
        dataType: "jsonp", 
        data: { 
            key: "KEY", 
            addressLine: options.address, 
            countryRegion: 'US', 
            userLocation: options.latitude + ',' + options.longitude, 
            maxResults: options.maxResults, 
        }, 
        jsonp: "jsonp", 
        success: function(data) { 
            if (options.success instanceof Function) { 
                options.success(data); 
            } 
        }, 
        error: function(xhr, status, text) { 
            alert('ERROR:\n\n'); 
        } 
    }); 
};