【问题标题】:Get Current GeoLocation in Javascript在 Javascript 中获取当前地理位置
【发布时间】:2020-05-16 05:28:04
【问题描述】:

function showPosition() {
  navigator.geolocation.getCurrentPosition(showMap, error);
}

function showMap(position) {
  // Get location data
  var mylatlong = position.coords.latitude + "," + position.coords.longitude;

  // Set Google map source url
  var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";

  // Create and insert Google map
  document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />

<div id="embedMap">
  <!--Google map will be embedded here-->
</div>

我是 Javascript 和 HTML 的新手,目前正在测试如何在单击按钮后获取当前位置并在谷歌地图中显示它。我已经尝试过了,但我仍然无法在地图中获取我当前的位置。

app.js

function showPosition() {
             navigator.geolocation.getCurrentPosition(showMap);
         }

         function showMap(position) {
             // Get location data
             var latlong = position.coords.latitude + "," + position.coords.longitude;

             // Set Google map source url
             var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";

             // Create and insert Google map
             document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
         }

index.html

<input type="button" value="Add Map" onclick="showPosition()"/>
 <div id="embedMap">
        <!--Google map will be embedded here-->
    </div>

【问题讨论】:

  • 问题可能是地理定位已在本文档中被功能策略禁用。在使用此代码之前检查Is there a way to check if geolocation has been DECLINED with Javascript?
  • 您好,我已经尝试检查地理位置是否被拒绝,但它没有显示任何内容,并且地图仍然无法正常工作。
  • 我刚刚添加了sn-p。谢谢!
  • 我已经更新了演示。您在单击按钮时遇到任何错误吗?
  • 并非如此。我尝试以文本格式显示当前位置,我可以清楚地看到我的纬度和经度。我认为问题出在 mapLink 中。我还可以看到“谷歌地图”替代文字。只是地图没有显示。

标签: javascript html google-maps geolocation


【解决方案1】:

如果您想通过在 JavaScript 和 HTML 中使用地理定位来获取您的当前位置,您可能想查看 Google Maps API Javascript 的 sample code。这展示了如何通过使用浏览器的 HTML5 地理定位功能创建在 Google 地图上显示用户或设备地理位置的地图。用户必须同意位置共享,否则会显示错误。阅读有关 W3C 地理定位标准的更多信息。然后,这会将您的坐标映射到由 Maps JavaScript API 创建的地图。

这也是我制作的示例代码的 sn-p,它在单击“地理定位”按钮后对位置进行地理定位。请记住使用您自己的 API 密钥更改字符串 YOUR_API_KEY

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
  <button id="myBtn">Geolocate</button>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 10
        });
        infoWindow = new google.maps.InfoWindow;
document.getElementById("myBtn").addEventListener("click", function(){
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found: ' + pos.lat + ',' + pos.lng);
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }

    });    
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多