HTML on单击以获取具有地理位置的用户位置


<body>
     <script src="script.js"></script>
     <div id="map">Get your Location</div>
     <script async defer src="https://maps.googleapis.com/maps/api/js?key=(API_KEY)&callback=getLocation"></script>
</body>

我只想创建一个按钮,单击"获取您的位置"后将转到我的脚本.js中的 getLocation(( 函数。现在,我的代码只会在加载页面时显示我的位置,而不是在单击按钮后。谢谢

基于 w3schools,您可以使用以下代码:

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos) {
    //You have your locaton here
      console.log("Latitude: " + pos.coords.latitude +
        "Longitude: " + pos.coords.longitude);
    });
  } else {
    console.log("Geolocation is not supported by this browser.");
  }
}
<button onclick="getLocation()">Get Location</button>

一旦地图加载到您的 HTML 中,您的函数 getLocation 就会被调用,因为您已经在 Google 地图的 url 中将该方法作为回调传递。如果要在单击某个元素时调用函数,则应将onclick属性添加到该元素。在您的情况下,您想在单击div 时调用 getLocation,那么您应该执行以下操作: <div id"map" onclick="getLocation()">Get Your Location</div>

如果我

理解正确,您需要做的就是将其添加到您的div中:

<div id="map" onclick="getLocation()">Get your Location</div>

最新更新