How to set Google maps marker size dynamically

。_饼干妹妹 提交于 2020-01-26 04:12:19

问题


I am trying to size my marker by zooming, but it seems not to work here is the code for a better overview:

function Icon(url) {
    this.url = url;
    this.scaledSize = new google.maps.Size(30, 30); // scaled size
    //this.origin = new google.maps.Point(0,0); // origin
    //this.anchor = new google.maps.Point(0, 0); // anchor
}

var icon1 = new Icon('img/marker-test.png');

        map.addListener('zoom_changed', function() {
        if(map.zoom === 18){
            //marker.setIcon(test);
            console.log('check');
            marker.scaledSize = new google.maps.Size(300, 300);

        } else {
            //marker.setIcon(icon1);
        }
    });

Somebody knows how to fix this?


回答1:


Before I answer, a couple suggestions:

  • You have used map.zoom === 18which is not valid. It should be map.getZoom() === 18
  • marker.scaledSize is invalid as scaledSize is the property of Icon object. Ref:Icon Object Specification

    If you need to set the marker size dynamically, you need to specify the marker image(while creating marker) via icon property and not as a string or leave empty(to show default marker).

Scale wont work on default marker. So you need to provide your own custom image for the marker.

Scale vs Size

Scale transforms the marker image and size specifies the canvas size of the image. Setting size property of a small marker image will not show you any zoom effect of the marker image. However if the marker image is large enough and that it was previously been drawn with downscaling, upscaling will work fine.

If you just scale the image and not set the size, the marker image will zoom in the prespecifed size. That is some portions of the marker image will not be visible.

To put in easy words, here is a fiddle. Try changing zoom to 18 and over and then back to 15 and below.




回答2:


Try with the correct getZoom map method.

if (map.getZoom() === 18) {
    ...
}

https://developers.google.com/maps/documentation/javascript/reference#Map



来源:https://stackoverflow.com/questions/36397627/how-to-set-google-maps-marker-size-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!