我想在react native中用以下方法获取我的当前位置。响应本地地理定位 我得到了我的位置的纬度和经度。现在我想在不使用Google API密钥的情况下将它们转换为位置的地址。
有什么方法可以在不使用Google API key的情况下将经纬度转换为地址?
有很多方法可以在不使用谷歌地图API的情况下将lonlat转换为地址。搜索 reverse geocoding api
你会发现一堆替代品。
几个月前,我被Google收取了过高的反向地理编码API请求费用。所以我改用了 喏. 他们有一个 免费层 提供每月25万次请求,这对我的应用很有效。请看这里的文档。https:/developer.here.comdocumentationexamplesrestgeocoderreverse-geocode。这将给你提供高度详细的地址数据(不同于Muhammad建议的ip-api.com)。
这是我用来调用API的包装函数。
function getAddressFromCoordinates({ latitude, longitude }) {
return new Promise((resolve) => {
const url = `https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json?apiKey=${HERE_API_KEY}&mode=retrieveAddresses&prox=${latitude},${longitude}`
fetch(url)
.then(res => res.json())
.then((resJson) => {
// the response had a deeply nested structure :/
if (resJson
&& resJson.Response
&& resJson.Response.View
&& resJson.Response.View[0]
&& resJson.Response.View[0].Result
&& resJson.Response.View[0].Result[0]) {
resolve(resJson.Response.View[0].Result[0].Location.Address.Label)
} else {
resolve()
}
})
.catch((e) => {
console.log('Error in getAddressFromCoordinates', e)
resolve()
})
})
}
不如果没有API密钥,就无法获得准确的地址。
如果你想获得IP基地的位置,那么你可以使用下面的IP-base-API与fetch。
fetch('http://ip-api.com/json')
.then((response) => response.json())
.then((response) => {
console.log('User\'s Location Data is ', response);
console.log('User\'s Country ', response.country);
})
.catch((error) => {
console.error(error);
});
但是你可以用免费的配额获得反向地理编码,比如colakollektiv答案。
https:/developer.here.comdocumentationgeocoderdev_guidetopicsexample-reverse-geocoding.html。
function getAddressFromCoordinates({ latitude, longitude }) {
return new Promise((resolve) => {
const url = `https://reverse.geocoder.ls.hereapi.com/6.2/reversegeocode.json?apiKey=${HERE_API_KEY}&mode=retrieveAddresses&prox=${latitude},${longitude}`
fetch(url)
.then(res => res.json())
.then((resJson) => {
// the response had a deeply nested structure :/
if (resJson
&& resJson.Response
&& resJson.Response.View
&& resJson.Response.View[0]
&& resJson.Response.View[0].Result
&& resJson.Response.View[0].Result[0]) {
resolve(resJson.Response.View[0].Result[0].Location.Address.Label)
} else {
resolve()
}
})
.catch((e) => {
console.log('Error in getAddressFromCoordinates', e)
resolve()
})
})
}