将javascript变量存储到HTML文本框中

时间:2015-02-11 00:47:05

标签: javascript html5 gps geolocation

我正在使用HTML5地理位置,并希望将纬度和经度存储到两个单独的文本框中,而不是简单地显示在屏幕上

以下是代码:

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>

2 个答案:

答案 0 :(得分:1)

假设您要设置值的两个文本框是:

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

您可以在JS中添加以下行以选择相应的文本框并存储该值。

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

答案 1 :(得分:0)

您需要在页面上放置一对文本框,并设置其value

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 + "'> ";


}