Google Maps Javascript地图中心更新

时间:2019-03-09 19:26:57

标签: javascript html google-maps

全部

我绝不是JavaScript程序员,主要是从头到尾地重复使用/重新使用摘要来完成任务。我目前正在尝试解决Google地图的局限性,即除非您自己滚动地图,否则地图不可样式(AFAICT)。我有一个工作的HTML页面,其中包含一个Google地图,该页面正确使用Google地图样式和地理位置将地图中心设置为用户的位置。

我的问题:

如果页面打开时用户的位置发生变化,如何使地图居中显示在用户的位置?

搜索,因为我可能找不到通过JavaScript更新地理位置的示例。可能这是不可能的,可能是Google的API文档很薄弱,或者是我的Google-fu太臭了。可能全部三个。

我的代码(几乎完全从Google Maps文档中获取):

 <body>
    <div id="map"></div>
    <script>
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 38.391677, lng: -97.661646},
          zoom: 17,
          styles: [...]
        });
        infoWindow = new google.maps.InfoWindow;
        // 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.'); 
            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=********************************&callback=initMap">
</script>
  </body>

2 个答案:

答案 0 :(得分:0)

要检测地理位置的变化,可以使用watchPosition方法。 (尽管并非所有浏览器都支持)。

当您有一组新的坐标时,您可以调用setCenter,它将为您定位地图的中心。

有一个blog post here似乎准确地描述了您要做什么。

答案 1 :(得分:0)

假设将中心的初始设置设置为当前位置有效,则只需将代码包装在setInterval调用中即可每隔几秒钟重复设置中心:

if (navigator.geolocation) {
  setInterval(function() {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.'); 
      infoWindow.open(map);
      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  }, 1000); // 1000 = number of milliseconds after which to repeat the call, i.e. 1 second
} else {
  // Browser doesn't support Geolocation
  handleLocationError(false, infoWindow, map.getCenter());
}

我不确定,是否真的希望在每次调用时都显示infoWindow和错误消息,但是基本知识都存在。