【问题标题】:Resizing custom image marker with zoom - Google Maps API v3使用缩放调整自定义图像标记的大小 - Google Maps API v3
【发布时间】:2016-12-28 05:29:26
【问题描述】:

我正在使用自定义图像作为 Google Map API 的图标/标记。我希望标记图像在用户放大地图时调整大小。

我采用了这个问题的一些代码:Google Maps :: Changing icon based on zoom level

不幸的是,此脚本仅更改我列表中的最后一个纬度/经度标记。我不知道为什么,谁能指出我的错误?

代码如下:

var locations = [
 ['Aaron Baddeley (130)',-25.274398,133.775136],
 ['Adam Hadwin (176)',52.939916,-106.450864],
 ['Adam Scott (7)',-26.65,153.066667],
 ['Adilson da Silva (291)',-28.530554,30.895824],
 ['Alejandro Canizares (167)',40.416775,-3.70379],];

var infowindow = new google.maps.InfoWindow({}

var image = new google.maps.MarkerImage('images/marker11.gif',
  new google.maps.Size(9,9), //size
    null, //origin
    null, //anchor
    new google.maps.Size(9,9) //scale
);

var marker, i;
for (i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
  position: new google.maps.LatLng(locations[i][1], locations[i][2]),
  map: map,
  icon: image,
});

//when the map zoom changes, resize the icon based on the zoom level so the marker covers the same geographic area
google.maps.event.addListener(map, 'zoom_changed', function() {
  var pixelSizeAtZoom4 = 9; //the size of the icon at zoom level 4
  var maxPixelSize = 350; //restricts the maximum size of the icon, otherwise the browser will choke at higher zoom levels trying to scale an image to millions of pixels

  var zoom = map.getZoom();
  var relativePixelSize = Math.round(pixelSizeAtZoom4*Math.pow(1.2,zoom)); // use 2 to the power of current zoom to calculate relative pixel size.  Base of exponent is 2 because relative size should double every time you zoom in

  if(relativePixelSize > maxPixelSize) //restrict the maximum size of the icon
   relativePixelSize = maxPixelSize;

  if(zoom < 4) //when zooming < 4, fix pixel size to 9
   relativePixelSize = 9;


//change the size of the icon

marker.setIcon(
    new google.maps.MarkerImage(
        marker.getIcon().url,  //marker's same icon graphic
        null,//size
        null,//origin
        null, //anchor
        new google.maps.Size(relativePixelSize, relativePixelSize) //changes the scale
    )
);        
});

【问题讨论】:

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


【解决方案1】:

为触发标记图标更改的zoom_changed事件添加事件侦听器

map.addListener('zoom_changed', function() {
    for (var i=0, len = locations.length; i < len; i++) { 
       // set new icon depending on the value of map.getZoom()
       markers[i].setIcon(...) 
    }
});

在 for 循环中创建标记时,应将标记保存在数组 markers 中,以便将它们引用为 markers[i]

【讨论】:

  • 感谢您的回复!在创建数组方面,我很不喜欢,所以我尝试使用不同的方法,基本上根据缩放级别调整相同标记的大小。
猜你喜欢
  • 2011-10-12
  • 2011-03-17
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
  • 2013-09-14
相关资源
最近更新 更多