根据缩放Google地图v3调整标记大小

Mad*_*sen 15 google-maps-api-3

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

也许我必须删除地图更改缩放的所有内容并创建不同大小的新标记?

小智 30

每次缩放地图时,此代码都会调整大小,因此它始终覆盖相同的地理区域.

//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
        )
    );        
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的代码.显然,MarkerImage已被弃用并被删除.立即使用 - > https://developers.google.com/maps/documentation/javascript/markers#convertingtoicon (2认同)

Cra*_*gma 12

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

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

  • 您也可以将其挂钩到zoom_changed事件,例如:google.maps.event.addListener(map,"zoom_changed",function(){var zoom = map.getZoom(); //根据当前缩放执行某些操作} ); (6认同)