我使用Nominatim API从纬度和经度获取用户的地址(使用geolocation HTML5 API获取它们)。这是我的geolocation API代码块:
function geoFindMe() {
function success(position) {
localStorage.setItem('pos_lat', position.coords.latitude);
localStorage.setItem('pos_lon', position.coords.longitude);
}
function error() {
elLocation.textContent = 'Unable to retrieve your location';
}
if (!navigator.geolocation) {
elLocation.textContent = 'Geolocation is not supported by your browser';
} else {
elLocation.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
}
我将用户的纬度和经度保存在本地存储中,因为我没有找到返回这些值的方法。我需要这些,因为在其他函数中,我使用Nominatim API从lat和lon获取地址。
现在,我的问题是,用户第一次访问网站时,他的localStorage是空的。并且当用户不允许我知道他的位置时,地址不能被获取。我的解决方案是在用户允许后刷新页面,但我不知道如何做,有人可以帮助我这个或其他解决方案?
编辑:我将只添加获取地址的代码块:
async function getLocationData() {
geoFindMe();
const latitude = localStorage.getItem('pos_lat');
const longitude = localStorage.getItem('pos_lon');
let url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;
const response = await fetch(url);
if(!response.ok) throw response;
const data = await response.json();
let locationAddress = {};
locationAddress.village = data.address.village;
locationAddress.city = data.address.city;
locationAddress.country = data.address.country;
locationAddress.countryCode = data.address.country_code;
return locationAddress;
}
发布于 2019-04-18 08:51:58
试试这样的..。
function getLocationData() {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(success, fail);
} else {
return 'Sorry, your browser does not support geolocation services.';
}
}
async function success(position) {
let url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${position.coords.latitude}&lon=${position.coords.longitude}`;
const response = await fetch(url);
if (!response.ok) throw response;
const data = await response.json();
let locationAddress = {};
locationAddress.village = data.address.village;
locationAddress.city = data.address.city;
locationAddress.country = data.address.country;
locationAddress.countryCode = data.address.country_code;
console.log(locationAddress);
return locationAddress;
}
function fail() {
return 'Fail...';
}
console.log(getLocationData())
发布于 2019-04-18 21:25:28
我最终用coords返回了一个Promise,而不是使用localStorage,并且它起作用了:)
function geoFindMe() {
return new Promise((resolve) => {
if (!navigator.geolocation) {
error('Geolocation is not supported by your browser');
} else {
elLocation.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(resolve, error);
}
});
function error() {
elLocation.textContent = 'Unable to retrieve your location';
elNewsList.firstElementChild.textContent = 'Unable to retrieve your country news';
}
}
async function getLocationAddress() {
const { latitude, longitude } = (await geoFindMe()).coords;
let url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;
}
不管怎样,还是要感谢你的帮助!
https://stackoverflow.com/questions/55730280
复制相似问题