2015-02-11 11 views
0

我使用的是HTML5地理位置,並希望存儲的緯度和經度爲兩個獨立的文本框,而不是屏幕存儲javascript變量成HTML文本框中

下面就被簡單地顯示是代碼:

Current Location: <BR> 

<button onclick="getLocation()">Locate</button> 
<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; 

} 
</script> 

回答

0

您需要在頁面上有一對文本框,並設置它們的value s。

Current Location: <BR> 

<button onclick="getLocation()">Locate</button> 
<p id="demo"> 
    Latitude: <input type="text" id="lat"> 
    Longitude: <input type="text" id="lon"> 
</p> 

<script> 
    function getLocation() { 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(showPosition); 
     } else { 
      x.innerHTML = "Geolocation is not supported by this browser."; 
     } 
} 

    function showPosition(position) { 
     document.getElementById("lat").value = position.coords.latitude; 
     document.getElementById("lon").value = position.coords.longitude; 

} 
</script> 

您還可以通過用JavaScript編寫出來的文本框做到這一點:

function showPosition(position) { 
     x.innerHTML = "Latitude: <input type='text' id='lat' value='" + position.coords.latitude + "'> " + 
     "Longitude: <input type='text' id='lon' value='" + position.coords.longitude + "'> "; 


} 
+0

嗯是的,但你也可以生成文本框,如果他們不存在 – 2015-02-11 01:04:19

+0

@DustinPoissant請參閱我的答案的第二部分。 – Hydrothermal 2015-02-11 01:04:40

1

假設你想在設定值的兩個文本框分別是:

Latitude: <input type="text" id="lat"><br> 
Longitude: <input type="text" id="long"> 

你可以添加以下行到您的JS選擇適當的文本框並存儲值。

document.getElementById("lat").setAttribute("value", position.coords.latitude);