点击一个按钮,谷歌地图应该至少适合3个离你当前位置点最近的标记

Google maps should fit at least 3 nearest markers to your current location point, by clicking a button

本文关键字:3个 最近 位置 一个 按钮 谷歌地图      更新时间:2024-04-01

我有一个按钮,可以将您重定向到地图上的当前位置,但重定向到位置后,地图应该会自动缩放,您应该能够看到至少3个最近的标记。

这是我代码的一部分。它唯一能做的就是适合绑定到所有标记,但不会显示我的位置

 $('a.geolocation').click(function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var bounds = new google.maps.LatLngBounds();
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      for (var i=0; i<storeLocator.markers.length; i++) {
          if(storeLocator.markers[i].getVisible()) {
              bounds.extend( storeLocator.markers[i].getPosition() );
          }
      }
      map.setCenter(pos);
      map.fitBounds(bounds);
    });
  }
});

发生的事情就是这样。您将地图的中心设置为用户的位置。但是,然后你让地图符合你的商店的边界,这将调整地图的中心,而不一定让你的用户的位置可见。

你所需要做的就是确保这个位置也在边界内。

navigator.geolocation.getCurrentPosition(function(position) {
    var bounds = new google.maps.LatLngBounds();
    var pos = new google.maps.LatLng(
        position.coords.latitude,
        position.coords.longitude
    );
    bounds.extend(pos);
    for (var i=0; i<storeLocator.markers.length; i++) {
        if(storeLocator.markers[i].getVisible()) {
            bounds.extend( storeLocator.markers[i].getPosition() );
        }
    }
    map.setCenter(pos);
    map.fitBounds(bounds);
});