代码之家  ›  专栏  ›  技术社区  ›  Luke

让谷歌地图以地理位置为中心并适当放大

  •  8
  • Luke  · 技术社区  · 16 年前

    我想将x数量的地理位置传递给谷歌地图API,并让它围绕这些位置居中,并设置适当的缩放级别,以便在地图上看到所有位置。即显示地图上当前的所有标记。

    默认情况下,谷歌地图API提供的功能是否可能实现这一点,或者我是否需要自己解决这个问题?

    4 回复  |  直到 13 年前
        1
  •  3
  •   carson    16 年前

    有很多种方法可以做到这一点,但是如果您使用的是V2 API,那么这非常容易。看到这个 post for an example , this group post this post .

        2
  •  9
  •   C. K. Young    14 年前

    我用过 fitBounds (API v3)各点:

    1. 声明变量。

      var bounds = new google.maps.LatLngBounds();
      
    2. 用for循环遍历每个标记

      for (i = 0; i < markers.length; i++) {
          var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
          bounds.extend(latlng);
      }
      
    3. 最后呼叫

      map.fitBounds(bounds);
      
        3
  •  2
  •   Andrew    15 年前

    对于V3来说 zoomToMarkers

        4
  •  1
  •   Nasser Al-Wohaibi    13 年前

    格雷的想法很好,但效果并不理想。我得为一个 动物标记 API V3:

    function zoomToMarkers(map, markers)
    {
        if(markers[0]) // make sure at least one marker is there
        {
            // Get LatLng of the first marker
            var tempmark =markers[0].getPosition();
    
            // LatLngBounds needs two LatLng objects to be constructed
            var bounds = new google.maps.LatLngBounds(tempmark,tempmark);
    
            // loop thru all markers and extend the LatLngBounds object
            for (var i = 0; i < markers.length; i++) 
            {
                bounds.extend(markers[i].getPosition());
            }
    
            // Set the map viewport 
            map.fitBounds(bounds);
        }
    
    }