基于路线的中心地图

时间:2013-09-12 21:32:14

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

我想根据路线的中心点居中谷歌地图,但我不能使用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());

第二次更新:请删除投票结果。这是一个很容易回答的合理问题。

2 个答案:

答案 0 :(得分:2)

DirectionsRoute有bounds - 属性(LatLngBounds - 对象)。 LatLngBounds有一个center - 属性,因此您需要做的就是将地图的center设置为center bounds的{​​{1}} 1}}:

route

答案 1 :(得分:0)

如果您使用Google JS API在您的网站上显示Google Map,则可以根据其包含的标记,将其自动居中和自动缩放。

添加标记之前:

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

相关问题