<html>
<body>
<p id="GeoElem">
</p>
//按下此按钮时,我应该使用Func2
中计算的值重定向到url<button id="myButton2" onClick=myFunct3()> Click me </button>
<script>
//构建我的网址的函数; Func2返回undefined
function myFunc3() {
window.location.href = window.location.href + "/search/" + Func2();
}
//需要Func2来调用Geo,它计算元素内部html中的位置
function Func2() {
Geo();
var x = document.getElementById("GeoElem");
return strip(x.innerHTML); //return the innerHTML
}
//应该在名为GeoElem
的元素的innerHTML中存储位置function Geo() {
var x = document.getElementById("GeoElem");
function showPosition(position) {
x.innerHTML = position.coords.latitude + ";" + position.coords.longitude;
}
if (navigator.geolocation) {
x.innerHTML = navigator.geolocation.getCurrentPosition(showPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
//return x.innerHTML;
}
//此函数应返回纯文本,删除html
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
</script>
</body>
</html>
=============== 证明我的主函数(Geo)有效:但是,当你把所有东西放在一起时,就像上面的例子一样,它在url中返回undefined而不是坐标。
这是一个功能性示例,它在html元素中返回屏幕上的坐标,但我希望它们由上面尝试过的函数返回
<p id="idx"></p>
<script>
var x = document.getElementById("idx");
function showPosition(position) {
x.innerHTML = position.coords.latitude + ";" + position.coords.longitude;
}
if (navigator.geolocation) {
x.innerHTML = navigator.geolocation.getCurrentPosition(showPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
</script>
请注意。将函数Geo直接返回的坐标更好,而不将它们存储到元素的innerHTML中,但这不起作用:
function handle_geolocation_query() {
navigator.geolocation.getCurrentPosition(function (position) {
var position = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var lat = position.lat;
var long = position.lng;
return (lat + ';' + long);
})
}
两种方法中的任何一种都可以。要么直接计算并从函数返回,要么通过html元素抓取它并将其传递给window.location.href = window.location.href + "/search/" + handle_geolocation_query();
myFunct3
答案 0 :(得分:0)
function myFunction() {
var x = document.getElementById("id22");
function showPosition(position) { //When the user allows Geolocation, you could get the position, otherwise you can't
x.innerHTML = position !== undefined ? position.coords.latitude + ";" + position.coords.longitude : "You don't have allow Geo";
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition); //At this point, the Geolocation is ever undefined
x.innerHTML = 'Please allow Geo!';
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
函数navigator.geolocation.getCurrentPosition
不会返回任何内容(另请参阅https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition),因此默认情况下它返回undefined。
希望有所帮助。