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 に答える