问题描述
我在 Cordova 中开发了一个开源 APP(它使用 Javascript)并且我正在使用 Google Maps API,尽管随着 APP 越来越受欢迎,我的账单也在增加(对于免费、无广告的 APP 来说不太好) .因此,我想转向 Open Street Maps。
我一直在阅读有关 Overpass API 的 docs,但没有看到简单清晰的代码实现示例。我知道要使用的 sever,我应该使用 HTTP GET 请求并使用它们特殊的 XML 语法。但不清楚如何将该 XML 传递给 GET 请求。此外,关于坐标的例子提供了一个边界框作为输入,而不是一个点(或者一个点被认为是一个角相同的正方形?)。
<union>
<bbox-query s="51.249" w="7.148" n="51.251" e="7.152"/>
<recurse type="up"/>
</union>
<print mode="meta"/>
您能否提供一个简单的 Javascript 示例(例如使用 $.ajax
),说明如何通过向 API 提供地理坐标来获取某个位置的地址?
解决方法
几个小时后,我与您分享了可行的解决方案。显然,我们应该使用 Open Street Maps 的 Nominatim 服务,以及反向地理编码服务。请阅读usage policy以避免滥用,因为这是一项完全免费的服务。
$.ajax({
url: "https://nominatim.openstreetmap.org/reverse",data: {
lat: 38.748666,lon: -9.103002,format: "json"
},beforeSend: function (xhr) {
xhr.setRequestHeader(
'User-Agent','ID of your APP/service/website/etc. v0.1'
)
},dataType: "json",type: "GET",async: true,crossDomain: true
}).done(function (res) {
console.log(res.address)
}).fail(function (error) {
console.error(error)
})