映射API Javascript函数调用错误

Maps API Javascript function calling fault

本文关键字:错误 函数调用 Javascript API 映射      更新时间:2023-09-26

我一直在使用addPoly函数的内容到初始化函数,它完美地工作。但是如果我创建一个addPoly函数并从初始化函数调用它,它将不起作用。我想让用户选择一个形状。因此,点击一个按钮,我可以调用特定的形状函数。

<!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>

您的函数addPoly()尝试使用变量map两次,尽管它仅在function initialize()中本地定义。

尝试初始化你的地图一次onload和使map全局像你做了shape和调用function addPoly()直接从你的选择代码-然后这个问题应该解决。

HTH安迪