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

时间:2010-07-19 13:36:38

标签: google-maps-api-3

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

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

3 个答案:

答案 0 :(得分:27)

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

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

答案 1 :(得分:11)

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

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

答案 2 :(得分:0)

要按照缩放级别将图像添加到地图,请使用 GroundOverlay。

https://developers.google.com/maps/documentation/javascript/groundoverlays