获取位置值以填充文本框javascript

时间:2016-07-21 06:53:08

标签: javascript

我试图让GPS坐标填充在此沙箱的文本框中:https://jsfiddle.net/8pkmrsj7/

function geoFindMe() {
    var output = document.getElementById("out");

    if (!navigator.geolocation){
        output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
        return;
    }

    function success(position) {
        var loc  = position.coords.latitude + ',' + position.coords.longitude;
        output.innerHTML =  loc ;
    };

    function error() {
        output.innerHTML = "Unable to retrieve your location";
    };

    output.innerHTML = "<p>Locating…</p>";

    navigator.geolocation.getCurrentPosition(success, error);
};
    <p>
        <button onclick="geoFindMe()">Show my location</button>
    </p>
    <div id="out"></div>
</div>
<input type="text" id="out" />

我很近,但我只是遗漏了一些东西。有什么指针吗?

1 个答案:

答案 0 :(得分:1)

您有2个具有相同ID的元素,因此请将输入设为out_input

<body>
  <p><button onclick="geoFindMe()">Show my location</button></p>
  <div id="out"></div>
  <input type = "text" id = "out_input"/>
</body>

将输入值更新设置为文本框:

  function success(position) {
    var loc  = position.coords.latitude + ',' + position.coords.longitude;
    document.getElementById("out_input").value =  loc ;
  };