首页 > 解决方案 > 谷歌地图 fitBound 不是第一次放大多条线

问题描述

我正在使用 fitbound 函数在地图的折线上自动缩放。但是如果我更改chartData并再次调用相同的函数,它第一次不能正常工作它工作正常。功能代码如下。

var mapOptions = {
                    zoom: 1,
                    center: { lat: 0, lng: 0 },
                    zoomControl: true,
                    zoomControlOptions: {
                        style: google.maps.ZoomControlStyle.SMALL
                    },
                    mapTypeId: 'satellite'
                };
                this.chart = new google.maps.Map(document.getElementById(chart_element.id), mapOptions);
                let polylinePath = new google.maps.Polyline({
                    path: chart_data,
                    geodesic: true,
                    strokeColor: '#FF0000',
                    strokeOpacity: 1.0,
                    strokeWeight: 2
                });

                /* set auto zoom level to polyline */

                var latlngbounds = new google.maps.LatLngBounds();
                for (var i = 0; i < this.chartData.length; i++) {
                    latlngbounds.extend(this.chartData[i]);
                }

                this.chart.fitBounds(latlngbounds);

                /* Set polyline chart to map */
                polylinePath.setMap(this.chart);

在此处输入图像描述

标签: javascriptgoogle-maps

解决方案


getBounds()您可以向:添加一个原型方法,然后通过首先设置地图然后拟合边界来根据'sgoogle.maps.Polyline缩放。MapPolylineLatLngBounds

polyline.setMap(map);
map.fitBounds(polyline.getBounds());

此外,您的代码中的路径被调用一次chart_data,然后this.chartData......

var map;
var timeout;
var coordinates = [
  {lat: 37.772, lng: -122.214},
  {lat: 21.291, lng: -157.821},
  {lat: -18.142, lng: 178.431},
  {lat: -27.467, lng: 153.027}
];

var polyline = new google.maps.Polyline({
  path: coordinates,
  geodesic: true,
  strokeColor: '#FFD034',
  strokeOpacity: 1.0,
  strokeWeight: 2
});

var mapOptions = {
  mapTypeId: 'satellite',
  zoom: 20,
  zoomControl: true,
  zoomControlOptions: {
    style: google.maps.ZoomControlStyle.SMALL
  }
};

google.maps.Polyline.prototype.getBounds = function() {
  var bounds = new google.maps.LatLngBounds();
  this.getPath().forEach(function(e) {bounds.extend(e);});
  return bounds;
};

function onLoad() {

  /* creating the map and plotting the polyline */
  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);  
  polyline.setMap(map);
  
  /* initially fitting the map to bounds */
  map.fitBounds(polyline.getBounds());
  
  /* subsequent events, which fit the map to bounds (may prevent manual zoom). */
  google.maps.event.addListener(map, 'bounds_changed',
    function() {
      window.clearTimeout(timeout);
      timeout = window.setTimeout(function () {
        map.fitBounds(polyline.getBounds());
      }, 500);
    }
  );
}
google.maps.event.addDomListener(window, "load", onLoad);
html, body, #map_canvas {height: 100%; width: 100%; margin: 0px; padding: 0px;}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>


推荐阅读