[英]Maps API Javascript function calling fault
I have been using the contents of the addPoly function into the initialize function and it works perfectly. 我一直在将addPoly函数的内容用于initialize函数中,并且它运行良好。 But if i make a function addPoly and call it from the initialize function, it won't work.
但是,如果我创建一个函数addPoly并从initialize函数调用它,它将无法正常工作。 I want to make a user to select a shape.
我想让用户选择形状。 Thus onclick of a button i can call the particular shape function.
因此,单击按钮时,我可以调用特定的形状函数。
<!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:
<select id="selectType">
<option type="button" value="Polygon" onclick="initialize()">Polygon</option>
<option type="button" value="Circle" onclick="initialize()">Circle</option>
</select>
</body>
</html>
Your function addPoly() tries to use the variable map
twice although is is defined only locally in the function initialize()
. 尽管函数addPoly()仅在
function initialize()
本地定义,但它尝试两次使用变量map
。
Try to initialize your map once onload and make map
global like you did with shape
and call the function addPoly()
directly from your select-code - then this problem should be solved. 尝试在
function addPoly()
初始化地图,并像使用shape
一样使map
全局map
,然后直接从选择代码中调用function addPoly()
-然后应解决此问题。
HTH Andy 安迪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.