我已经开始使用本教程向GMaps v3地图添加自定义控件:
https://developers.google.com/maps/documentation/javascript/controls?hl=fr#CustomControls
最后一个示例特别演示了如何使用控件保存状态。我所拥有的是两个控件应该串联起来,因为当单击控件A时,它应该明显更改为粗体文本,并将B控制为普通文本,并且当单击B时,控件A将被重置。我试图通过保存状态来做到这一点,在这种情况下是按钮的“选定”状态,但我不知道在重置按钮组中的非选定按钮方面下一步该去哪里,更改按钮字体 - 重量等等。
简而言之,我试图重现一个与原生地图类型选择按钮具有相同行为的按钮组。
有关如何最好地解决此问题的任何教程或指示?我将重新发布上面链接示例中的代码,因为我的属性基本相同,只是我的属性被称为selected_
。
// Define a property to hold the Home state.
CustomControl.prototype.selected_ = null;
// Define setters and getters for this property.
CustomControl.prototype.getSelected = function() {
return this.selected_;
}
CustomControl.prototype.setSelected = function(selected) {
this.selected_ = selected;
}
function CustomControl(map, div, selected) {
// Get the control DIV. We'll attach our control UI to this DIV.
var controlDiv = div;
// We set up a variable for the 'this' keyword since we're adding event
// listeners later and 'this' will be out of scope.
var control = this;
// Set the home property upon construction.
control.selected_ = selected;
// styling removed //
// Setup the click event listener
google.maps.event.addDomListener(setSelectedUI, 'click', function() {
control.setSelected(true);
});
}
尝试使用按钮存储所选状态时,我是否会采用完全错误的方法?
答案 0 :(得分:0)
您可以遍历所有控件(在给定的controlPosition处),比较当前节点是否为选定节点,并修改样式
示例(将为活动控件提供className“selected
”并清除每个其他控件的className,因此您可以使用全局样式表来应用样式)
google.maps.event.addDomListener(setSelectedUI, 'click', function() {
var _this=this;
map.controls[google.maps.ControlPosition.TOP_RIGHT]
.forEach(function(node){
node.className=(node==_this.parentNode)?'selected':''
});
/* proceed with your control-action*/
});
我不确定代码中是什么setSelectedUI
,但您必须将addDomListener
的第一个参数设置为函数中与controlUI
具有相同含义的对象。相关的例子。