我有这个位置脚本:
<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<p id="demo"> </p>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
window.onload = getLocation();
</script>
</body>
</html>
它完美无缺,但我想做的是再一次在我体内显示坐标而不复制相同的脚本。我只想要像PHP代码echo $ coords这样的东西?
答案 0 :(得分:1)
只需调用getLocation并传递您想要坐标的元素ID。
function getLocation(elem) {
var x = document.getElementById(elem);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
}
getLocation('demo');
getLocation('demo1');
HTML:
<p id="demo"> </p>
<p id="demo1"> </p>
答案 1 :(得分:0)
停止使用x
作为全局。使它成为getLocation()的参数(并给它一个更有意图的显示名称)。
showPosition
只能从getLocation
调用,在getLocation
内定义,然后才能使用相同的变量。
function getLocation(target_element) {
function showPosition(position) {
target_element.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
target_element.innerHTML = "Geolocation is not supported by this browser.";
}
}
getLocation(document.getElementById("demo"));
getLocation(document.getElementById("some_other_element"));
答案 2 :(得分:-1)
<body>
<p id="demo"> </p>
<script>
window.onload = getLocation();
var x=document.getElementById("demo");
var locationString="";
function getLocation(){ /*the rest of your code */ }
function showPosition(position)
{
locationString = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
x.innerHTML=locationString;
}
</script>
<!-- the rest of HTML here -->
<p><script>document.write(locationString);</script></p>
</body>
</html>