如何将CSS-Class添加到GoogleMaps标记?

Bas*_*ber 18 google-maps google-maps-api-3 google-maps-markers

我想在我的GoogleMaps应用程序(Web)中为标记设置动画(fadein,fadeout).

如何将任何css类分配给标记?

或者我如何访问特定标记?他们有选择器,如:之后还是什么?

如果没有,那么应用动画的最简单方法是什么?

Dr.*_*lle 17

包含用于标记的图像的DOMNode无法通过API获得.

此外,默认情况下,标记不是单个DOM节点,它们将通过画布绘制.

但是,当您为每个标记使用唯一的图标URL时,可以通过CSS访问标记图像.


示例(使用jQuery):

<style type="text/css">
img[src^='http://www.google.com/mapfiles/marker.png?i=']{
  opacity: 0.5
}
</style>
<script  type="text/javascript">
      function initialize() {
        var index=0;
        var mapOptions = {
          zoom: 14,
          center: new google.maps.LatLng(52.5498783, 13.425209099999961),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            mapOptions);

        marker=new google.maps.Marker({position:map.getCenter(),
                 map:map,optimized:false,
                 icon:'http://www.google.com/mapfiles/marker.png?i='+(index++)});

        google.maps.event.addListener(marker,'mouseover',function(){
          $('img[src="'+this.icon+'"]').stop().animate({opacity:1});
        });

        google.maps.event.addListener(marker,'mouseout',function(){
          $('img[src="'+this.icon+'"]').stop().animate({opacity:.5});
        });
      }

      google.maps.event.addDomListener(window, 'load', initialize);

</script> 
Run Code Online (Sandbox Code Playgroud)

它是如何工作的:

该示例使用单个图像作为Marker-Icon(http://www.google.com/mapfiles/marker.png)

通过CSS我们应用不透明度.您可能会注意到URL中有一个i参数.此参数将用于使img-src唯一.

我使用一个变量来增加一个唯一的img-src:

var index=0;

//a few lines later:
icon:'http://www.google.com/mapfiles/marker.png?i='+(index++)
Run Code Online (Sandbox Code Playgroud)

现在,您将能够<img/>通过属性选择器选择用于标记的元素,例如onmouseover/onmouseout.

当您不想使用vanilla javascript时,您可能会使用它document.querySelector来访问图像.

注意:您必须将optimized标记的-option 设置为false(这将强制API将标记呈现为单个元素)
演示: http://jsfiddle.net/doktormolle/nBsh4/

  • 自Google Maps v3起,您无法再访问此类自定义图片标记:(.请尝试访问https://developers.google.com/maps/documentation/javascript/examples/icon-simple并输入`文档. querySelectorAll('img [src*= beachflag]')`在控制台中. (2认同)