2017-10-16 257 views
1

有一個谷歌地圖上點作爲標記上傳。有必要通過點進行路線建設:用鼠標右鍵單擊該點,並將該點添加到路線中。 我不明白如何通過地圖上的對象數組來製作鼠標單擊事件的處理程序。在Yandex Maps上,它是這樣做的:標記事件點擊谷歌地圖

myMap.geoObjects.events.add ('contextmenu', function (e) {}) 

那麼Google地圖呢?這個想法應該是這樣的:

google.maps.Marker.addListener ('rightclick', function (e) {}) 

但這種方法是行不通的。我如何實現事件處理? enter image description here

回答

3

我假設你的觀點已經在數組中。如果是這樣,您只需循環訪問陣列中的每個點,然後創建一個新的Google Marker實例並填寫屬性(,您可以查看here對於Google標記文檔)。然後在每個標記中,附加一個偵聽器,當單擊「右鍵單擊」時,它將在您的路線上添加新的目標。有關事件的更多信息,請查看this文檔。

這裏是一個示例實現:

<div id="map"></div> 
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> 
<script type="text/javascript"> 
    function initMap(){ 
     var sampleCoords = [ { lat:14.599512, lng:120.98422 },{ lat:14.554729, lng:121.024445 },{ lat:14.579444, lng:121.035917 } ]; 
     var options = { center : { lat: 14.5995, lng:120.9842 }, zoom : 10, streetViewControl : false }; 
     var map = new google.maps.Map(document.getElementById('map'), options); 
     for (var key in sampleCoords) { 
      sampleCoords[key] = new google.maps.Marker({ 
       position : new google.maps.LatLng(sampleCoords[key].lat,sampleCoords[key].lng), 
       map : map, 
       title : 'test' 
      }); 
      sampleCoords[key].addListener('rightclick', function(params){ 
       alert('Right clicked!') 
      }); 
     } 
    } 
</script> 

工作演示here

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
     <title>Add Route to Map Onclick</title> 
 
     <style type="text/css"> 
 
      html,body,#map { 
 
       width:100%; 
 
       height:100%; 
 
      } 
 
     </style> 
 
    </head> 
 
    <body> 
 
     <div id="map"></div> 
 
     <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap"></script> 
 
     <script type="text/javascript"> 
 
      function initMap(){ 
 
       var sampleCoords = [ { lat:14.599512, lng:120.98422 },{ lat:14.554729, lng:121.024445 },{ lat:14.579444, lng:121.035917 } ]; 
 
       var options = { center : { lat: 14.5995, lng:120.9842 }, zoom : 10, streetViewControl : false }; 
 
       var map = new google.maps.Map(document.getElementById('map'), options); 
 
       for (var key in sampleCoords) { 
 
        sampleCoords[key] = new google.maps.Marker({ 
 
         position : new google.maps.LatLng(sampleCoords[key].lat,sampleCoords[key].lng), 
 
         map : map, 
 
         title : 'test' 
 
        }); 
 
        sampleCoords[key].addListener('rightclick', function(params){ 
 
         alert('Right clicked!'); 
 
        }); 
 
       } 
 
      } 
 
     </script> 
 
    </body> 
 
</html>

希望它能幫助!

+0

非常感謝! – Roman69

+0

如果有幫助,請考慮接受/提高我的答案。謝謝:) – rafon

+0

好,完成!謝謝) – Roman69

相關問題