谷歌地图视口自动调整

时间:2014-06-27 16:35:51

标签: google-maps-api-3

我在这个jsfiddle找到了由@Chad Killingsworth创建的一些不错的动画路线,我只是想问一下是否可以自动调整地图的视口,以便我们可以看到它前进的路线。

function initialize() {
  var mapOptions = {
    zoom: 14,
    center: new google.maps.LatLng("54.32216667","10.16530167"),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  var path_start = new Array();
  var path_end = new Array();

  path_start.push(new google.maps.LatLng("54.32216667","10.16530167"));
  path_end.push(new google.maps.LatLng("54.32216667","10.16530167"));

  // lots of other points

  path_start.push(new google.maps.LatLng("54.36457667","10.12173333"));
  path_end.push(new google.maps.LatLng("54.36457833","10.121745"));

  var carPolyline = new google.maps.Polyline({
    map: map,
    geodesic : true,
    strokeColor : '#FF0000',
    strokeOpacity : 1.0,
    strokeWeight : 2
  });
  var carPath = new google.maps.MVCArray();
  for ( var i = 0; i < path_start.length; i++) {
    if(i === 0) {
      carPath.push(path_start[i]);
      carPolyline.setPath(carPath);
    } else {
      setTimeout((function(latLng) {
        return function() {
          carPath.push(latLng);
        };
      })(path_start[i]), 100 * i);
    }
  }

提前谢谢。

1 个答案:

答案 0 :(得分:1)

添加:

map.setCenter(latLng);

到绘制折线的代码。

  var carPath = new google.maps.MVCArray();
  for ( var i = 0; i < path_start.length; i++) {
    if(i === 0) {
      carPath.push(path_start[i]);
      carPolyline.setPath(carPath);
    } else {
      setTimeout((function(latLng) {
        return function() {
          carPath.push(latLng);
          map.setCenter(latLng);
        };
      })(path_start[i]), 100 * i);
    }
  }

updated fiddle