Javascript 将地理位置作为字符串变量传递
Javascript pass geolocation as string variable
我想用地理定位标记相机照片(坐标很好)。
这是我的一段代码:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
return position.coords.latitude + " " + position.coords.longitude;
}
在方法 takePhoto() 中我有:
...
context.drawImage(video, 0, 0, 640, 480);
var loc = getLocation();
context.strokeText(loc, 10, 50);
...
我的问题是我不知道如何传递保存位置坐标的变量,我尝试了很多方法但没有成功。有人有什么想法吗?
谢谢。
编辑:我希望它看起来像这样:
您需要异步等待才能解决此问题
function takePhoto(position) {
document.getElementById("x").innerHTML = position.coords.latitude + " " + position.coords.longitude;
}
function getLocation() {
return new Promise((resolve,reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
return resolve(position);
}, function(err) {
return reject(err);
});
} else {
return reject("Geolocation is not supported by this browser.");
}
})
}
(async function() {
const coords = await getLocation();
takePhoto(coords);
})().then(() => {
console.log("done")
}).catch((err) => {
console.error(err);
})
<div id="x">empty</div>
我想用地理定位标记相机照片(坐标很好)。 这是我的一段代码:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
return position.coords.latitude + " " + position.coords.longitude;
}
在方法 takePhoto() 中我有:
...
context.drawImage(video, 0, 0, 640, 480);
var loc = getLocation();
context.strokeText(loc, 10, 50);
...
我的问题是我不知道如何传递保存位置坐标的变量,我尝试了很多方法但没有成功。有人有什么想法吗?
谢谢。
编辑:我希望它看起来像这样:
您需要异步等待才能解决此问题
function takePhoto(position) {
document.getElementById("x").innerHTML = position.coords.latitude + " " + position.coords.longitude;
}
function getLocation() {
return new Promise((resolve,reject) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
return resolve(position);
}, function(err) {
return reject(err);
});
} else {
return reject("Geolocation is not supported by this browser.");
}
})
}
(async function() {
const coords = await getLocation();
takePhoto(coords);
})().then(() => {
console.log("done")
}).catch((err) => {
console.error(err);
})
<div id="x">empty</div>