我写JS应用程序,在那里我使用点阵列绘制了很多多段线,但在平均点中,我在这一点上有一些额外的属性(GPS数据、速度等)。
我想在mouseover或onmouseclick事件中显示这些额外的道具。
我有两种方法:
-
使用标准多段线和事件处理程序。但在这种情况下,我无法确定该多段线起点的其他属性,因为我无法将这些道具保存在多段线属性中。有一个解决方案-在数组中保存额外的属性,并尝试通过多段线第一点的LatLng来找到它们,但我想这太慢了。。
-
扩展折线并在新对象中保存其他属性,但我不能扩展鼠标事件:(
要扩展多段线,我使用以下代码:
function myPolyline(prop, opts){
this.prop = prop;
this.Polyline = new google.maps.Polyline(opts);
}
myPolyline.prototype.setMap = function(map) {
return this.Polyline.setMap(map);
}
myPolyline.prototype.getPath = function() {
return this.Polyline.getPath();
}
myPolyline.prototype.addListener= function(prop) {
return this.Polyline.addListener();
}
myPolyline.prototype.getProp= function() {
return this.prop;
}
myPolyline.prototype.setProp= function(prop) {
return this.prop = prop;
}
并在for循环中创建新对象(i-点阵列中当前点的索引),如下所示:
var polyline_opts = {
path: line_points,
strokeColor: color,
geodesic: true,
strokeOpacity: 0.5,
strokeWeight: 4,
icons: [
{
icon: lineSymbol,
offset: '25px',
repeat: '50px'
}
],
map: map
};
var add_prop = {
id: i,
device_id: device_id
};
...
devices_properties[device_id].tracks[(i-1)] = new myPolyline(add_prop, polyline_opts);
其中:
- line_points-点阵列(仅两个点)
- i-当前点索引
- devices_properties[device_id].tracks-根据我的device_id索引的扩展多段线阵列(带添加属性)
之后,我设置了这样的事件处理程序:
var tmp = devices_properties[device_id].tracks[(i-1)];
google.maps.event.addListener(tmp.Polyline, 'click', function(e) {
...
console.log(tmp.prop.id);
...
}
但在这种情况下,我总是在控制台中得到相同的id。。
当我使用时
google.maps.event.addListener(devices_properties[device_id].tracks[(i-1)].Polyline, 'click', function(e) {
...
console.log(???); // How to get parent of polyline fired the event?
...
}
我不知道如何让折线的父对象触发事件?
我回答了我自己的问题-已经完成了,我只是在使用"for"而不是"$.each"时遇到了一些问题:)
使用前:
for ( i = 1; i < devices_properties[device_id].history_points.length; i++ ) {
...
create myPolyline
...
}
它不起作用——创建了一个事件句柄。
之后:
$.each(devices_properties[device_id].history_points, function(i, tmp){
...
create myPolyline ()
...
}
它很有效——创建了很多事件处理程序。
为了处理事件,我使用这个:
google.maps.event.addListener(c_polyline.Polyline, 'mouseover', function(e) {
var prop = c_polyline.getProp();
...
console.log(prop.id, prop.device_id);
}