【问题标题】:Extend polyline and handle mouse event延长折线并处理鼠标事件
【发布时间】:2017-10-27 03:14:39
【问题描述】:

我编写了 JS 应用程序,在其中我使用点数组绘制了很多折线,但在每一点我在这一点上都有一些额外的属性(GPS 数据、速度等)。

我想在 onmouseover 或 onmouseclick 事件中显示这些额外的道具。

我有两种方法:

  1. 使用标准折线和事件处理程序。但在这种情况下,我无法确定此折线起点的其他属性,因为我无法将这些道具保存在折线属性中。有一个解决方案 - 将附加属性保存在数组中,并尝试通过折线第一个点的 LatLng 找到它们,但我猜它太慢了..

  2. 扩展折线并在新对象中保存其他属性,但我无法扩展鼠标事件:(

要扩展折线,我使用以下代码:

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”时遇到了一些麻烦 :)

标签: google-maps-api-3 event-handling mouseevent polyline extending


【解决方案1】:

我回答了我自己的问题 - 已经完成了,我只是在使用“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);
}

【讨论】:

  • 你有没有弄清楚为什么 for 循环实现不起作用?如果可能的话,我会尽量避免使用 jQuery,因为我的应用程序的其他地方不需要它。
猜你喜欢
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多