【发布时间】:2019-04-29 08:29:51
【问题描述】:
我正在使用 Nominatim API 从纬度和经度中获取用户的地址(使用地理定位 HTML5 API 来获取这些)。 这是我的地理定位 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 从纬度和经度获取地址。
现在,我的问题是,用户第一次访问该网站时,他的 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;
}
【问题讨论】: