【问题标题】:Center Map based on Route基于路线的中心地图
【发布时间】:2013-09-12 21:32:14
【问题描述】:

我想根据路线的中心点将 Google 地图居中,但我不能使用 fitbounds,因为它不允许我使用自定义缩放(它会缩放到路线的边界) .

以下是我目前的尝试。我想知道是否可以使用map.setCenter?我已经注释掉了我认为需要帮助的行。

google.maps.event.addListener(dr, 'directions_changed', function() {
  var route = dr.getDirections().routes[0];
  var path = route.overview_path;
  es.getElevationAlongPath({
    path: path,
    samples: Math.max(50, path.length * 2)
  }, function(result, status) {
    if (status == google.maps.ElevationStatus.OK) {
      drawElevation(result);
      recalcHeight();
      if (fitBounds) {
        map.setZoom(route.bounds);
       //map.setCenter();
        fitBounds = false;

      }
    }
    else {
      $('#error').text(status).show();
    }
    recalcHeight();
  });
});

更新:这个简单的更改解决了我的问题 - 自定义缩放,然后正确居中:

map.setZoom(13);
map.setCenter(route.bounds.getCenter());

第二次更新:请删除投反对票。这是一个合理的问题,答案很简单。

【问题讨论】:

  • 您如何看待“路线的中心点”——东西极端和南北极端之间的中间点?为什么不想使用fitbounds
  • 这是XY Problem。 XY 问题是询问您尝试的解决方案,而不是您的实际问题。也就是说,您正在尝试解决问题 X,并且您认为解决方案 Y(路线中心上的中心图)会起作用,但是当您遇到麻烦时,您不会询问 X,而是询问 Y。
  • @Floris fitbounds 不允许我设置自定义缩放。
  • @ErikPhilips 那么你有什么建议呢?

标签: javascript function google-maps google-maps-api-3


【解决方案1】:

DirectionsRoute 有一个bounds-property(一个LatLngBounds-object)。 LatLngBounds有一个center-property,所​​以你需要做的就是把地图的center设置为boundsboundscenterroute

map.setCenter(route.bounds.getCenter());

【讨论】:

  • 这似乎没有使地图居中,@Dr.Molle
  • 您认为它还有什么作用?
  • 这部分代码:map.setZoom(route.bounds); 是错误的,会导致错误并停止进一步的脚本执行。你可以写map.setZoom('need coffee');,效果一样。
  • 你想让我猜为什么它是错的吗? :D @Dr.Molle
  • setZoom() 需要一个整数作为参数,而不是 LatLngBounds(route.bounds 就是这样)
【解决方案2】:

如果您使用 Google JS API 在您的网站上显示 Google 地图,您可以通过以下方法使其自动居中并根据其包含的标记自动缩放。

添加标记之前:

bounds = new google.maps.LatLngBounds();

每次添加新标记时:

loc = new google.maps.LatLng(marker.position.lat(),marker.position.lng()); bounds.extend(loc);

添加所有标记后:

map.fitBounds(bounds); # auto-zoom map.panToBounds(bounds); # auto-center

就是这样,干杯。

我是从这里找到的:Link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多