javascript - Google Map API v3 — 设置边界和中心

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

我最近切换到了 Google Maps API V3。我正在研究一个从数组中绘制标记的简单示例,但是我不知道如何相对于标记自动居中和缩放。

我在网上搜索过,包括谷歌自己的文档,但没有找到明确的答案。我知道我可以简单地取坐标的平均值,但是如何相应地设置缩放?

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),


    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

  setMarkers(map, beaches);
}


var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.423036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 121.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.450198, 151.259302, 1]
];

function setMarkers(map, locations) {

  var image = new google.maps.MarkerImage('images/beachflag.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
    var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',

      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));


      var lat = map.getCenter().lat(); 
      var lng = map.getCenter().lng();      


  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

最佳答案

是的,您可以声明新的边界对象。

 var bounds = new google.maps.LatLngBounds();

然后对于每个标记,扩展您的边界对象:

bounds.extend(myLatLng);
map.fitBounds(bounds);

API:google.maps.LatLngBounds

关于javascript - Google Map API v3 — 设置边界和中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1556921/

相关文章:

javascript - 使用 Requirejs 通过 Highcharts 加载 'theme' 和 'exporting' 模块

google-maps - 如何避免最终用户手动启动 Google Places Autocomplete 下拉菜单?

javascript - 确定一条路线是否属于谷歌地图中的另一条路线

javascript - 使用 Google Map V3 API 调用 infoWindow

php - 从 PHP 生成 Javascript/ExtJS 代码的最可维护的方法是什么?

javascript - 如何在 Jquery 脚本上定义子元素

javascript - Google map - 添加道路方向、圆圈、邮政编码区域

jquery - 带有点击处理程序和滚动条的 Google map 信息框

javascript - 谷歌地图在 UI 和标记上方添加叠加层

javascript - 将一个数分解为 100 的因数并保留余数