2010-07-19 279 views
9

我有一个在v3 API上运行的Google地图,我添加了一些自定义标记,是否可以根据地图的缩放级别进行缩放? 我试着搜索引用,但似乎找不到任何方法来调整MarkerImage的大小。根据缩放大小调整标记Google地图v3

也许我必须删除标记地图变化的所有东西放大并创建不同大小的新标记?

回答

7

不幸的是,你将不得不每次都设置图标。但是,您可以预先定义它们,然后将它们应用于标记。

zoomIcons = [null, icon1, icon2]; // No such thing as zoom level 0. A global variable or define within object. 
marker.setIcon(zoomIcons[map.getZoom()]); 
+2

也可以勾这对一个事件ZOOM_CHANGED,如: google.maps.event.addListener(地图, “部分zoom_changed”,函数(){风险变焦= map.getZoom(); //做取决于当前缩放的东西}); – Dr1Ku 2010-07-29 07:53:43

24

此代码将调整每次地图缩放时的大小,因此它总是覆盖相同的地理区域。

//create a marker image with the path to your graphic and the size of your graphic 
var markerImage = new google.maps.MarkerImage(
    'myIcon.png', 
    new google.maps.Size(8,8), //size 
    null, //origin 
    null, //anchor 
    new google.maps.Size(8,8) //scale 
); 

var marker = new google.maps.Marker({ 
    position: new google.maps.LatLng(38, -98), 
    map: map, 
    icon: markerImage //set the markers icon to the MarkerImage 
}); 

//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 pixelSizeAtZoom0 = 8; //the size of the icon at zoom level 0 
    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(pixelSizeAtZoom0*Math.pow(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; 

    //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 
     ) 
    );   
}); 
+0

谢谢你这个工作!我还喜欢缩放覆盖地理部分的额外步骤。但是对于我来说,标记是符号的,所以我只是使用map.getZoom()上的比较条件来适当地缩放它们。 – efwjames 2014-03-16 23:09:04

+1

感谢您的代码。显然MarkerImage已被弃用和删除。立即使用此功能 - > https://developers.google.com/maps/documentation/javascript/markers#convertingtoicon – 2017-03-31 19:11:56

相关问题