我想清除谷歌地图上的现有多边形,然后在点击提交按钮时在谷歌地图上自动新多边形。我的HTML代码看起来像这样。
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.9&
libraries=drawing"></script>
<script type="text/javascript" src="draw_on_map.js"></script>
</head>
<body>
<div id="map-canvas" class="gmap-con"></div>
<input type="text" id="search_polygon" name="search_polygon" value="">
<input type="submit" name="search_polygon" value="search_polygon"
onclick="getPolygon();">
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', draw_map_initialize);
</script>
</body>
</html>
我的javascript文件看起来像这样
function draw_map_initialize() {
var mapHeight = '400px';
// Set default height to Maps Containers
$('#map-canvas').css('height', mapHeight);
// Initialize map with markers(47.53187912201915, 7.705222390807307)
mymap = new GMaps({
div: '#map-canvas',
lat: 47.53187912201915,
lng: 7.705222390807307,
zoom: 20,
zoomControl: true,
mapTypeId: 'satellite'
});
map = mymap
drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
drawingModes: [
google.maps.drawing.OverlayType.MARKER,
google.maps.drawing.OverlayType.POLYGON
]
},
//drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
map: map
});
}
function getPolygons(){
var polygon_name = document.getElementById("search_polygon").value;
$.ajax({
url: url_prefix + "getPolygons",
data: ({
'polygon_name': polygon_name,
'as_json': 1
}),
async: false,
dataType: "json",
success: function(data) {
polygon_points = JSON.stringify(data);
if (polygon_points.length === 2){
alert('Sorry,No Area Stored with name '+polygon_name)
}
else{
var result = {};
var count = 1;
var path = [];
for (var key in data) {
obj = {
'name': key,
'coords': data[key]
};
result['area' + count++] = obj;
}
var polygon_coordinates = JSON.parse(polygon_points.replace(/u/g"").replace(/'/g,
'"').replace(/\(/g, "[").replace(/\)/g, "]"));
var polygon_start_latlng;
for (var poly in polygon_coordinates) {
for (var i = 0; i < polygon_coordinates[poly].length; i++) {
polygon_start_latlng = polygon_coordinates[poly][0]
}
}
polygon_start_lat = polygon_start_latlng[0]
polygon_start_lng = polygon_start_latlng[1]
if (map === undefined) {
draw_map_initialize();
}
map = sac_handler_map;
map.setCenter(area_start_lat, area_start_lng);
map.setZoom(30);
var my_area;
for (key in result) {
my_area = map.drawPolygon({
paths: result[key].coords,
title: result[key].name,
draggable: true,
editable: true,
strokeColor: 'black',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
}
}
},
error: function(data, status, e) {
alert(e);
}
});
}
我所做的是,当用户在文本框中键入多边形名称时,搜索它并显示谷歌地图。我可以搜索多边形并在地图上显示它。现在我想知道当用户键入并搜索新多边形时,如何清除谷歌地图上先前搜索和显示的多边形。我尝试使用my_area.setMap(null),但它没有按预期工作。
答案 0 :(得分:0)
将my_area声明为全局变量,即在javascript文件的开头添加以下声明。
var my_area;
你在哪里写下面的方法?
my_area.setMap(null)
让我知道它是否有效