如何将Javascript位置(经度和纬度)值传递给Textbox值?

时间:2015-11-12 07:02:15

标签: javascript html html5

<body>
    <button onclick="getLocation()">Get coordinates</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>
    <input type="text" value="long,lati"></input>
</body>


我需要将脚本中的纬度和经度放入文本框中,而无需在代码中按下按钮。

3 个答案:

答案 0 :(得分:1)

<input type="text" value = "" id='loc'>
window.onload = function(){
 var x = document.getElementById('loc');
      function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        } else {
            x.value = "Geolocation is not supported by this browser.";
        }
     }

     function showPosition(position) {
        x.value = "Latitude: " + position.coords.latitude +     ",Longitude: " + position.coords.longitude;
    }
getLocation();
};

只需抓住输入元素并将其值attr设置为获得的lat&amp;长 。 这不是很好的解决方案,但它应该完成你需要的工作(不点击按钮)。

答案 1 :(得分:0)

        <body>
            <button>Get coordinates</button>
            <p id="demo"></p>
            <script>

                var x = document.getElementById("demo");

               getLocation();

                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>
            <input type="text" value="long,lati"></input>
        </body>

答案 2 :(得分:0)

要在文本框中获取纬度和经度,您需要获取文本框的ID并传递lat long的值

这是一个Jsfiddle http://jsfiddle.net/2b4n03k1/

var x = document.getElementById("demo");


function showPositionInInput(position) {
 var input = document.getElementById("location");
 input.value = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}

function showPosition(position) {
 x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}

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

getLocation()