Javascript 使用来自 Google Maps API v3 中精灵的标记图标缩放标记大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6811313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scaling marker size with marker icons from a sprite in Google Maps API v3
提问by Maxim Zaslavsky
I'm playing with the Google Maps API (v3) and I've run into an issue with marker icons. I'm trying to vary the size of my markers depending on their individual data attributes.
我正在使用 Google Maps API (v3),但遇到了标记图标问题。我正在尝试根据标记的各个数据属性来改变标记的大小。
The icons themselves are in a sprite that contains three different circular markers, each 16px by 16px. I'm trying to scale individual icons, but am so far unsuccessful.
图标本身位于包含三个不同圆形标记的精灵中,每个标记为 16 像素 x 16 像素。我正在尝试缩放单个图标,但到目前为止还没有成功。
Here's my code:
这是我的代码:
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
)
});
The problem seems to be at the last line, where I'm trying to scale the marker icon to the desired size. Instead of it scaling properly, I'm getting a weird, distorted ellipse-shaped icon.
问题似乎出现在最后一行,我试图将标记图标缩放到所需的大小。我得到了一个奇怪的、扭曲的椭圆形图标,而不是正确缩放。
What am I doing wrong?
我究竟做错了什么?
回答by Maxim Zaslavsky
After some trial and error, I have figured out how this is supposed to work (the documentation is deceiving), thanks to this blog post.
多亏了这篇博文,经过一些试验和错误,我已经弄清楚这应该如何工作(文档是骗人的)。
Here's my new code:
这是我的新代码:
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
)
});
Hope this helps someone down the line!
希望这可以帮助某人!