Масштабирование размера маркера с помощью значков маркеров из спрайта в Google Maps API v3 - PullRequest
14 голосов
/ 25 июля 2011

Я играю с Google Maps API (v3) и столкнулся с проблемой значков маркеров. Я пытаюсь изменить размер моих маркеров в зависимости от их отдельных атрибутов данных.

Сами значки находятся в спрайте, который содержит три разных круглых маркера, каждый по 16 на 16 пикселей. Я пытаюсь масштабировать отдельные значки , но пока безуспешно.

Вот мой код:

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 Ответ

22 голосов
/ 25 июля 2011

После некоторых проб и ошибок я выяснил, как это должно работать (документация обманчива), благодаря этому сообщению в блоге .

Вот мой новый код:

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

Надеюсь, это поможет кому-то в дальнейшем!

...