我有多边形,多边形和带孔的多边形。他们都很好。我们正在放置一个引脚(Marker),然后在有人选择不同的多边形时移动标记。 [编辑:有数百个多边形,所以手动重新设置它们就像下面的答案一样不实用]
我们想要的是用fillColor替换标记。当有人点击多边形时,我可以轻松更改fillColor - 这不是问题。当有人点击不同的多边形时,我遇到的问题是尝试清除fillColor。
这是一个包含许多文件的大项目......但相关部分在这里:
//building is the polygon
building.addListener('click', function() {
// We've been using markers, can we can easily move them.
setMarker(map, this.center, true);
// Want to use this instead. This works fine to color the polygon but...
this.setOptions({
fillColor: 'orange'
});
// I need some function, likely to be called here that clears any other polygon that has been change to 'orange'.
// I was looking at map.data.revertStyle(); but this doesn't work at this level.
});
为了说清楚,如果有人再次点击它,有很多例子可以重置多边形。这很容易做到。我希望在单击不同的多边形时重置,就像移动标记功能的工作方式一样。
谢谢
答案 0 :(得分:0)
您可以让map
收听自定义resetColor
事件,并在您的多边形点击功能上触发此事件,如下所示:
var map;
function initMap() {
//initialize map...
// Define the LatLng coordinates for the polygons paths.
// Construct the polygon.
//add polygons to map
//attach the map to our custom -resetColor- event
google.maps.event.addListener(map, "resetColor", function(){
resetColor.call(bermudaTriangle, null); //invoke resetColor making sure 'this' is the bermuda triangle
resetColor.call(secondTriangle, null); // 'this' is the second triangle
resetColor.call(someOtherTriangle, null); // ditto
});
bermudaTriangle.addListener("click", selectedColor); //polygon1
secondTriangle.addListener("click", selectedColor); //polygon2
someOtherTriangle.addListener("click", selectedColor); //polygon3
}
google.maps.event.addDomListener(window, "load", initMap);
function resetColor() {
console.log("in trigger function");
this.setOptions({
fillColor: "black"
});
}
function selectedColor() {
//function executed on polygon click
google.maps.event.trigger(map, "resetColor"); //trigger our custom event on the map
this.setOptions({
fillColor: "yellow" //make the clicked polygon 'selected'
});
}
请参阅this pen以查看其是否有效。
上面的代码是开放的改进,欢迎任何想法。
答案 1 :(得分:0)
这就是我们最终接近这一点的方式。如果有人有更好的解决方案,请随意传递。这可能会帮助一些人...... 我正在创建一个单独的多边形,它只会保持单击的最后一个多边形。它会在点击任何其他多边形时重置。优点是它可以根据需要很好地工作。我不喜欢的部分是我正在创建一个单独的图层,如果可能的话,更改fillColor会很好。
var new_polygon = '';
// Checks for an "active" polygon, clears it if it exists, or sets a new one if it does not.
function active_polygon(center, polygon_latlng) {
if (new_polygon) {
new_polygon.setMap(null);
new_polygon = '';
}
new_polygon = new google.maps.Polygon({
map: map,
paths: polygon_latlng,
fillColor: "#DC4405",
center: center,
strokeWeight: 0,
fillOpacity: 1,
clickable: true,
zIndex: 400,
});
return new_polygon.setMap(map);
}
// this was my original listener above for polygons
// This is located in the polygon loop in a later part of the code.
building.addListener('click', function() {
// Generates the new polygon active later
active_polygon(this.center, this.getPaths());
});