【问题标题】:Center Google Map based on markers基于标记居中谷歌地图
【发布时间】:2018-05-10 02:50:45
【问题描述】:

我想根据动态加载的标记将 Google 地图居中。现在我在地图上显示两个标记(参见 script.js 文件):

$mapster.mapster('addMarker', {
  location: 'Golden Gate Bridge, San Francisco, CA',
  content: 'Example text 2'
});

$mapster.mapster('addMarker', {
  lat: 37.751350,
  lng: -122.485833,
  content: '<div style="color: #f00;">Example text 1</div>'
});

一切正常,因为我定义了使地图居中的坐标(参见 map-options.js 文件):

mapster.MAP_OPTIONS = {
  center: {
    lat: 37.791350,
    lng: -122.435883
  },
  zoom: 10,
  disableDefaultUI: false,
  scrollwheel: true,
  draggable: true,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  zoomControlOptions: {
    position: google.maps.ControlPosition.LEFT_BOTTOM,
    style: google.maps.ZoomControlStyle.DEFAULT
  },
  panControlOptions: {
    position: google.maps.ControlPosition.LEFT_BOTTOM
  },
  cluster: {
    options: {
      styles: [{
        url: 'https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclusterer/images/m2.png',
        height: 56,
        width: 55
        //textColor: '#000'
        //textSize: 12
      }, {
        url: 'https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclusterer/images/m1.png',
        height: 56,
        width: 55
        //textColor: '#000'
        //textSize: 12
      }]
    }
  },
  geocoder: true
};

如何根据已加载的标记将我的 Google 地图居中?我基本上想实现这样的目标: Center a Google Map based on Markers

这是我的代码: https://plnkr.co/edit/sduZKBXIIijhnkCIpSoR?p=preview

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 google-maps-markers centering


    【解决方案1】:

    如您链接的post 中所述,您需要在添加坐标时将坐标添加到bounds 对象,然后在其上调用fitBounds(bounds)。见documentation

    尝试遵循此控制流程:

    let location1 = new google.maps.LatLng(lat, lng);
    let location2 = new google.maps.LatLng(lat, lng);
    let location3 = new google.maps.LatLng(lat, lng);
    
    let marker = new google.maps.Marker({
        position: location1,
        map: map
    });
    
    marker = new google.maps.Marker({
        position: location2,
        map: map
    });
    
    marker = new google.maps.Marker({
      position: location3,
      map: map
    });
    
    let bounds = new google.maps.LatLngBounds();
    bounds.extend(location1);
    bounds.extend(location2);
    bounds.extend(location3);
    map.fitBounds(bounds);
    

    如果您的列表很长,您可能希望对数组或其他东西进行一些迭代。

    【讨论】:

      猜你喜欢
      • 2011-01-06
      • 2012-09-05
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多