【问题标题】:How do I replace the infoWindow with a circle to plot a users location如何用圆圈替换 infoWindow 以绘制用户位置
【发布时间】:2016-12-08 22:42:36
【问题描述】:

我正在使用带有 HTML5 地理位置的 infoWindow 的谷歌地图示例,并希望在地图上添加一个圆形标记以显示用户位置而不是 infoWindow 文本框。

我用谷歌搜索了但没有找到答案,这可能吗?

   var map;
function initMap(){
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6
  });
            var infoWindow = new google.maps.Circle({map: map});

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

            infoWindow.setCenter(pos);
            infoWindow.setContent('Location found.');
            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.');
      }
}

【问题讨论】:

标签: javascript google-maps geolocation


【解决方案1】:

google.maps.Circle 没有.setPosition 方法,它有.setCenter.setRadius 方法(尽管两者都可以在构造函数中设置。

proof of concept fiddle

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 0,
      lng: 0
    },
    zoom: 6
  });
  var circle = new google.maps.Circle({
    map: map,
    radius: 20000
  });

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

      map.setCenter(pos);
      circle.setCenter(pos);
      circle.setRadius(20000);
    }, function() {
      handleLocationError(true, circle, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, circle, map.getCenter());
  }

  function handleLocationError(browserHasGeolocation, circle, pos) {
    circle.setCenter(pos);
  }
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

【讨论】:

  • 谢谢,我看到了那个例子,但我没有看到 setCenter。
猜你喜欢
  • 2021-06-09
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多