2013-05-11 64 views
0

我一直在使用addPoly函數的內容進入初始化函數,它完美地工作。但是,如果我做一個函數addPoly並從初始化函數調用它,它將無法正常工作。我想讓用戶選擇一個形狀。因此,點擊一個按鈕我可以調用特定的形狀功能。Maps API Javascript函數調用錯誤

<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <style type="text/css"> 
    html,body {height:100%;} 
    #map-canvas {height:92%;width:100%;} 

    </style> 



    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> 
    <script type="text/javascript"> 

     var shape; 
     function initialize() { 
     var mapDiv = document.getElementById('map-canvas'); 
     var map = new google.maps.Map(mapDiv, { 
      center: new google.maps.LatLng(24.886436490787712, -70.2685546875), 
      zoom: 4, 
      mapTypeId: google.maps.MapTypeId.ROADMAP, 
      zoomControl: true 
     }); 

     addPoly();   
     } 

     function addPoly(){ 
     shape = new google.maps.Polygon({ 
      strokeColor: '#ff0000', 
      strokeOpacity: 0.8, 
      strokeWeight: 2, 
      fillColor: '#ff0000', 
      fillOpacity: 0.35 
     }); 
     shape.setMap(map); 
     google.maps.event.addListener(map, 'click', addPoint); 

     } 

     function clearAll(){  
     shape.setMap(null);  
     } 

     function addPoint(e) {  
     var vertices = shape.getPath(); 
     vertices.push(e.latLng);   
     } 

     google.maps.event.addDomListener(window, 'load', initialize); 
    </script> 
    </head> 
    <body style="font-family: Arial; border: 0 none;"> 
    <div id="map-canvas"></div> 
    <input type="button" value="Clear" onclick="clearAll()"> 
    Selection Type:&nbsp; 
    <select id="selectType"> 
     <option type="button" value="Polygon" onclick="initialize()">Polygon</option> 
     <option type="button" value="Circle" onclick="initialize()">Circle</option> 
    </select> 
    </body> 
</html> 

回答

0

你的功能addPoly()嘗試使用變量map兩次雖然是在function initialize()定義僅局部。

嘗試一次onload事件初始化地圖,讓map全球像你shape做了,直接從您的選擇代碼調用function addPoly() - 那麼這個問題應該得到解決。

HTH 安迪

+0

說真的,我一定是在幻覺!非常感謝你! – 2013-05-11 17:52:16