Google maps API:我只能加载一次地图

时间:2018-04-18 11:41:45

标签: javascript html html5 google-maps geolocation

我尝试使用HTML5地理定位和Google地图API来跟踪我的位置。我设置了一切,我第一次加载了我的页面。这一切看起来都很好,地图显示了我预期的区域,标记也在那里。

现在,每当我使用地理定位时,我都会发现一些非常烦人的事情。我可以加载地图一次没有问题。但是,当我尝试重新加载页面时,它绝对是空白的,它在控制台中没有给我任何错误。有谁知道为什么会这样?

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDFDGOMDXkdSHOkVaVbGjIwtMvqaTwVXCA"></script>
    <script type="text/javascript">
      var watchId, geocoder, startLat, startLong;
      var start = 1;

        window.onload = function(){

            if (navigator.geolocation){
                watchId = navigator.geolocation.watchPosition(success, onError, {maximumAge:60000, timeout:500000, enableHighAccuracy:true})
            }
      }
      function success(position){
          console.log('entered success')

          var currentLat = position.coords.latitude;
          var currentLong = position.coords.longitude;

          if (start === 1) {
              startLat = currentLat;
              startLong = currentLong;
              start = 0;
          }

          var geocoder = new google.maps.Geocoder();
          var latlong = new google.maps.LatLng(currentLat, currentLong);

          geocoder.geocode({'latLng': latlong}, function(result, status){
              if (status === google.maps.GeocoderStatus.OK){
                  document.getElementById("location").innerHTML = '<h2> Address is: ' + result[0].formatted_address + '</h2>'
              } else {
                  alert("Could not get the geolocation information")
              }
          });

          var mapOptions = {
              center: new google.maps.LatLng(startLat, startLong),
              zoom: 10,
              mapTypeId: google.maps.MapTypeId.ROADMAP
          };

          var map = new google.maps.Map(document.getElementById("mapArea"), mapOptions);

          var marker = new google.maps.Marker({
              position: new google.maps.LatLng(startLat, startLong),
              map: map,
              title: "My First Marker",
              animation: google.maps.Animation.DROP
              //    other effect is BOUNCE
          });

      }

      function onError(error){
          console.log(error);
      }
    </script>
  </head>
  <body>

  <div id="location">

  </div>
  <div id="mapArea" style="height:500px;width:500px;"></div>

  </body>
</html>

编辑:添加了DEV工具的网络标签

enter image description here

0 个答案:

没有答案