0

我有这个位置脚本:

<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>

<body>
 <p id="demo">&nbsp;</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 code echo $coords 之类的东西?

4

3 回答 3

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">&nbsp;</p>
<p id="demo1">&nbsp;</p>

工作演示

于 2012-11-18T16:04:11.303 回答
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"));
于 2012-11-18T16:04:13.020 回答
-1
<body>
<p id="demo">&nbsp;</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>
于 2012-11-18T16:14:03.243 回答