我正在使用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;
}
答案 0 :(得分:1)
尝试这样的事情...
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())
答案 1 :(得分:0)
我最终返回了一个带有坐标的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}`;
}
仍然感谢您的帮助!