添加标记后更改其锚点

时间:2018-11-22 13:12:19

标签: javascript google-maps google-maps-api-3 google-maps-markers

在创建Google Maps标记时,将icon参数用作对象或字符串时,性能可能会有所不同。

加载:

new google.maps.Marker({
      position: { lat: this.lat, lng: this.lng },
      map: this.map,
      icon: {url: iconUrl, anchor: anchor: new google.maps.Point(8, 8)
});

比加载它慢得多:

new google.maps.Marker({
      position: { lat: this.lat, lng: this.lng },
      map: this.map,
      icon: iconUrl
});

在加载大量点时可以看到,这给出了4500ms与400ms。

由于上面使用的图标是16x16px的圆圈,因此应在google.maps.Point(8, 8)中设置锚点。

是否可以以其他方式或在标记初始化之后设置锚点? 我可以在Google Maps文档中找到的唯一方法是在需要url参数的图标对象中传递锚参数的方法。

示例(在控制台中检查生成时间):https://jsfiddle.net/ur76jckb/

无论图标是否在base64中,是否存储在本地,其扩展名和大小都可以。只需将字段设置为对象或字符串即可。

Google地图v3.34.16

Bug reported

1 个答案:

答案 0 :(得分:0)

要在创建标记后更改标记图标的锚点,可以使用标记的setOptions()方法。

看看下面的示例,该示例创建标记并在3秒的延迟后更改其锚点。

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.88, 151.28),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(-33.781552, 151.274846),
        map: map,
        icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
    });
    
    window.setTimeout(function() {
        marker.setOptions({
            icon: { url:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
                anchor: new google.maps.Point(16,16)
            }
            
        });
    }, 3000);
            

}
html, body, #map {
     height: 100%;
     width: 100%;
     margin: 0px;
     padding: 0px;
 }
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" type="text/javascript"></script>

我希望这会有所帮助!