gpt4 book ai didi

javascript - 用户允许定位后刷新页面

转载 作者:行者123 更新时间:2023-12-02 23:48:47 25 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

尝试这样的事情......

  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())

关于javascript - 用户允许定位后刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com