2011-09-18 176 views
2

使用谷歌地图API v3,我的最终目的是创建一个给定长度和角度的箭头,但现在我试图创建一个SVG标记。我正在使用Rich Market utilityjquery.svg plugin。以下代码创建了div,但不创建SVG。建议? (我并不喜欢这些图书馆,但这些是我迄今发现的)。谷歌地图V3上的SVG标记

<head> 
<script type="text/javascript"> 
    var map, marker; 
    function drawCircle(svg) { 
     svg.circle(15, 15, 10, {fill: 'none', stroke: 'red', strokeWidth: 3}); 
    } 

    function div() { 
     var m = document.createElement('DIV'); 
     m.innerHTML = '<div class="arrow"></div>'; 
     $('.arrow').svg({onLoad: drawCircle}); 
     return m; 
    } 

    function init() { 
     map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 1, 
      center: new google.maps.LatLng(0, 0), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }); 

     marker = new RichMarker({ 
      map: map, 
      position: new google.maps.LatLng(30, 50), 
      draggable: true, 
      flat: true, 
      anchor: RichMarkerPosition.MIDDLE, 
      content: div() 
     }); 
    } 

    google.maps.event.addDomListener(window, 'load', init); 
</script> 
</head> 
<body><div id="map"></div></body> 

回答

3

问题出在div()函数。调用$('.arrow')与正在创建的div不匹配,因为它尚未附加到DOM节点树。您必须在创建标记后调用它。

div()删除$('.arrow').svg({onLoad: drawCircle});函数,稍后调用它。

function div() { 
    var m = document.createElement('DIV'); 
    m.innerHTML = '<div class="arrow"></div>'; 
    return m; 
} 

我想最好的办法是在init()函数的末尾添加在地图的闲置事件侦听器。

function init() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 1, 
     center: new google.maps.LatLng(0, 0), 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    marker = new RichMarker({ 
      map: map, 
     position: new google.maps.LatLng(30, 50), 
     draggable: true, 
     flat: true, 
     anchor: RichMarkerPosition.MIDDLE, 
     content: div() 
    }); 

    google.maps.event.addListenerOnce(map, 'idle', function() { 
     $('.arrow').svg({onLoad: drawCircle}); 
    }); 
} 
+0

谢谢。按预期工作。但是,我意识到我应该提出真正的问题,我现在已经在[http://stackoverflow.com/questions/7465191/creating-an-svg-marker-on-click-event] – punkish