【问题标题】:Get Latitude/Longitude Button to Fill Input Boxes获取纬度/经度按钮以填充输入框
【发布时间】:2012-01-30 16:41:52
【问题描述】:

我有两个文本框,希望用户填写地理位置数据(纬度和经度)。我想要一个按钮,所以当用户点击它时,文本框会立即被地理定位数据填充。

感谢 w3schools,我可以将两个段落标签中的文本替换为位置,但我希望按钮填充文本框。这就是我现在所拥有的。谁有答案?

<!DOCTYPE html>
<html>
<body>

<form>
Latitude: <input type="text" name="Latitude" /> <br />
Longitude: <input type="text" name="Longitude" />
</form>

<button onclick="getLocation()">Get Location</button><input type="submit" value="Submit" />

<p id="demo">Click the button to get your coordinates:</p>
<p id="demo2">Click the button to get your coordinates:</p>

<script>
var x=document.getElementById("demo");
var y=document.getElementById("demo2");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML=position.coords.latitude;  
  y.innerHTML=position.coords.longitude;    
  }
</script>

</body>
</html>

【问题讨论】:

    标签: html textbox geolocation latitude-longitude


    【解决方案1】:

    您并没有真正说出问题所在,但据我所知,innerHTML 仅适用于 FF 而不适用于 IE。试试:

    function showPosition(position) {
      x.value=position.coords.latitude;  
      y.value=position.coords.longitude;    
    }
    

    cmets 中要求的工作示例

    <!DOCTYPE html>
    <html>
    <body>
    
    <form>
    Latitude: <input id="demo" type="text" name="Latitude" /> <br />
    Longitude: <input id="demo2" type="text" name="Longitude" />
    </form>
    
    <button onclick="getLocation()">Get Location</button><input type="submit" value="Submit" />
    
    <p>Click the button to get your coordinates:</p>
    <p id="demo2">Click the button to get your coordinates:</p>
    
    <script>
    var x=document.getElementById("demo");
    var y=document.getElementById("demo2");
    function getLocation()
      {
      if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition);
        }
      else{x.innerHTML="Geolocation is not supported by this browser.";}
      }
    function showPosition(position)
      {
      x.value=position.coords.latitude;  
      y.value=position.coords.longitude;    
      }
    </script>
    
    </body>
    </html>
    

    【讨论】:

    • 抱歉不清楚,但您的解决方案有效!将 innerHTML 更改为 value,然后将 id="demo" 属性移动到 标记,将纬度/经度数据放入输入框中。谢谢!
    • 请给我们一个完整的工作示例...更改为上面的函数在问题的示例代码中不起作用。
    • @andrebruton 已更新。这已经存在很多年了,应该使用更好的方法,尽管它仍然有效。
    猜你喜欢
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2019-03-25
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多