这是一个老问题,但如果有人遇到这种问题,我会回答。我目前正在研究类似的任务,我必须创建可选择的道路。通过使用包含属性,侦听器和方法的JavaScript“类”,并使用setMap(map)函数在循环中将它们添加到地图画布中,我想出了一个解决方案。
基本上这会动态地创建带有可选区域的地图画布,但您仍然必须手动创建包含区域,其名称和其他信息及其坐标边界的数据集。
我认为使用此方法创建可选矩形,圆形,道路等其他具有悬停效果的对象也很容易。
伪代码:
function initialize() {
// initialize Google Maps canvas normally
// areaDataSet variable is an array of containing all areas to be
// drawed and the necessary information needed to create polygon areas
// (coordinate boundaries, and so on)
// For example var areaDataSet = [{ "name" : "Texas", "coords" : [latitudes and longitudes], "hasHotelsInCoords" : [...] }, { ... } ]
var areas = [];
for (i in areaDataSet) {
var area = new google.maps.Polygon({
path: [coordinates as google.maps.LatLng objects]
});
areas.push(new MyAreaClass(area));
}
for (i in areas) {
areas[i].setMap(map);
}
}
function MyAreaClass(areaData) {
this.area = areaData;
var selected = false; // not selected by default
// + all other data you want the areas to contain
// Add listeners using google.maps.event.addListener to all class instances
// when they are constructed.
// for instance:
google.maps.event.addListener(area, 'mouseover', function() {
if (selected == false) {
area.setOptions({ [options you want to set when area is hovered
but not selected, for instance, color change] });
};
else {
area.setOptions({ [options you want to set when area is hovered
and selected] });
};
});
// Add listeners also for when area is not hovered anymore, respectively,
// and other methods you might want to call when areas are being interacted with.
};
希望这有助于!
致以问候