使用Google Maps API v3中精灵的标记图标缩放标记大小

时间:2011-07-25 02:36:49

标签: javascript image google-maps google-maps-api-3 gis

我正在使用Google Maps API(v3),我遇到了标记图标的问题。我正在尝试根据各自的数据属性来改变标记的大小。

图标本身位于包含三个不同圆形标记的精灵中,每个标记为16px乘16px。我正在尝试扩展单个图标,但到目前为止还没有成功。

这是我的代码:

var offset = Math.floor(Math.random() * 3) * 16; // pick one of the three icons in the sprite

// Calculate desired pixel-size of the marker
var size = Math.floor(4*(count-1) + 8);

// Create custom marker
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    icon: new google.maps.MarkerImage(
        'img/dot.png', // my sprite with 3 circular icons
        new google.maps.Size(16, 16), // 16x16 is the original size of each individual icon
        new google.maps.Point(0, offset), // picking one of the three icons in the sprite
        new google.maps.Point(Math.floor(size/2), Math.floor(size/2)), // setting correct anchor for the marker
        new google.maps.Size(size, size) // trying to scale the marker
       )
    });

问题似乎出现在最后一行,我正在尝试将标记图标缩放到所需的大小。我没有正确缩放,而是得到一个奇怪的,扭曲的椭圆形图标

我做错了什么?

1 个答案:

答案 0 :(得分:22)

经过一些反复试验,我已经弄清楚这应该是怎样的(文档是骗人的),感谢this blog post

这是我的新代码:

var offset = Math.floor(Math.random() * 3) * 16; // pick one of the three icons in the sprite

// Calculate desired pixel-size of the marker
var size = Math.floor(4*(count-1) + 8);
var scaleFactor = size/16;

// Create custom marker
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    icon: new google.maps.MarkerImage(
        'img/dot.png', // my 16x48 sprite with 3 circular icons
        new google.maps.Size(16*scaleFactor, 16*scaleFactor), // desired size
        new google.maps.Point(0, offset*scaleFactor), // offset within the scaled sprite
        new google.maps.Point(size/2, size/2), // anchor point is half of the desired size
        new google.maps.Size(16*scaleFactor, 48*scaleFactor) // scaled size of the entire sprite
       )
    });

希望这可以帮助有人下线!