Javascript 将地理位置数据保存到Web存储
我正在尝试将Web存储实现到这个地理位置脚本中,它也显示了这个城镇。地理位置脚本工作正常,但每次刷新页面时,我都必须允许浏览器再次找到我的位置。我想将其存储在web存储中,但不知道将这部分代码放在何处:Javascript 将地理位置数据保存到Web存储,javascript,html,Javascript,Html,我正在尝试将Web存储实现到这个地理位置脚本中,它也显示了这个城镇。地理位置脚本工作正常,但每次刷新页面时,我都必须允许浏览器再次找到我的位置。我想将其存储在web存储中,但不知道将这部分代码放在何处: if (typeof(Storage) !== "undefined") { // Store localStorage.setItem("location", loc); // Retrieve document.getElementById("
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("location", loc);
// Retrieve
document.getElementById("json").innerHTML = localStorage.getItem("location");
} else {
document.getElementById("json").innerHTML = "Sorry, your browser does not support Web Storage...";
}
位置代码:
var x = document.getElementById("coordinate");
var y = document.getElementById("json");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Böngészője nem támogatja a helykeresést.";
}
}
function showPosition(position) {
x.innerHTML =
"Latitude: " +
position.coords.latitude +
"<br>Longitude: " +
position.coords.longitude;
//Create query for the API.
var latitude = "latitude=" + position.coords.latitude;
var longitude = "&longitude=" + position.coords.longitude;
var query = latitude + longitude + "&localityLanguage=hu";
document.cookie = "latitude=" + position.coords.latitude;
document.cookie = "longitude=" + position.coords.longitude;
const Http = new XMLHttpRequest();
var bigdatacloud_api =
"https://api.bigdatacloud.net/data/reverse-geocode-client?";
bigdatacloud_api += query;
Http.open("GET", bigdatacloud_api);
Http.send();
Http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
console.log(myObj);
y.innerHTML = "(" + myObj.locality + ")";
loc = myObj.locality;
//If I paste it here, it doesn't do anything.
}
};
//If I paste it here, the "loc" variable will be not defined.
}
var x=document.getElementById(“坐标”);
var y=document.getElementById(“json”);
函数getLocation(){
if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(showPosition);
}否则{
x、 innerHTML=“Böngészője nem támogatja a helykeresést.”;
}
}
功能显示位置(位置){
x、 innerHTML=
“纬度:”+
位置坐标纬度+
“
经度:”+
位置、坐标、经度;
//为API创建查询。
var latitude=“latitude=“+position.coords.latitude;
var longitude=“&longitude=“+position.coords.longitude;
变量查询=纬度+经度+“&LocationLanguage=hu”;
document.cookie=“latitude=“+position.coords.latitude;
document.cookie=“longide=“+position.coords.longide”;
const Http=new XMLHttpRequest();
var bigdatacloud\u api=
"https://api.bigdatacloud.net/data/reverse-geocode-client?";
bigdatacloud_api+=查询;
Http.open(“GET”,bigdatacloud_api);
Http.send();
Http.onreadystatechange=函数(){
if(this.readyState==4&&this.status==200){
var myObj=JSON.parse(this.responseText);
console.log(myObj);
y、 innerHTML=“(“+myObj.locality+”);
loc=myObj.locality;
//如果我把它贴在这里,它什么也不做。
}
};
//如果我将其粘贴到这里,则不会定义“loc”变量。
}