如何每次单击“创建新多边形”按钮时,将最后一个对象存储在数组中并创建一个新的干净对象以在 map 上绘制新的分离的折线。我想保留旧折线的功能。现在无法清洁该物体。下面提供了简化的示例。
HTML:
<button onclick="create()">Create New Poly</button>
<div id="map" style="width: 500px; height: 400px;"></div>
JS:
var map;
var listener;
var polys = [],
poly = {};
create = function() {
poly = new Poly();
if ( !! listener) google.maps.event.removeListener(listener);
listener = google.maps.event.addListener(map, 'click', function(e) {
poly.addPoint(e.latLng);
});
}
function Poly() {
this.markers = [];
this.setMap(map);
polys.push(this);
}
Poly.prototype = new google.maps.Polyline();
Poly.prototype.addPoint = function(p) {
var m = poly.createMarker(p);
poly.markers.push(m);
poly.getPath().push(p);
}
Poly.prototype.createMarker = function(p) {
var marker = new google.maps.Marker({
position: p
});
marker.setMap(this.getMap());
return marker;
}
$(function() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(48.864715, 10.546875),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
演示:JSFIDDLE
最佳答案
即使按照本·戴维斯的建议行事http://jsfiddle.net/LxGmR/它仍然存在问题。
我认为这是由于所有 Ploy 对象共享相同的原型(prototype):Poly.prototype = new google.maps.Polyline();
。我认为解决方法是每个新的 Ploy
对象都需要自己的原型(prototype) google.maps.Polyline
实例。
经过测试,我发现这是真的:http://jsfiddle.net/uhZFE/
然后我查找了如何在没有包装函数的情况下执行此操作,我使用了 SO 答案 https://stackoverflow.com/a/6519265/388787 中描述的方法( http://javascript.crockford.com/prototypal.html 也很有帮助)并生成 http://jsfiddle.net/YgSwF/这是以下内容;它按照您的要求工作:
var map;
var listener;
var polys = [];
create = function () {
var poly = new Poly();
if ( !! listener) google.maps.event.removeListener(listener);
listener = google.maps.event.addListener(map, 'click', function (e) {
poly.addPoint(e.latLng);
});
polys.push(poly);
}
function Poly() {
google.maps.Polyline.call(this);
this.markers = [];
this.setMap(map);
}
Poly.prototype = Object.create(google.maps.Polyline.prototype);
Poly.prototype.addPoint = function (p) {
var m = this.createMarker(p);
this.markers.push(m);
this.getPath().push(p);
}
Poly.prototype.createMarker = function (p) {
var marker = new google.maps.Marker({
position: p
});
marker.setMap(this.getMap());
return marker;
}
$(function () {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(48.864715, 10.546875),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
关于javascript - 每次单击按钮时如何创建新对象并将旧对象存储在数组中?面向对象的JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10711648/