javascript - 单击一条线并打开弹出窗口 OpenLayers 3

标签 javascript openlayers-3

我正在将 GPX 文件加载到我的 OL3 代码中。现在我想让 GPX 制作的整行都可以点击,并提供一些额外的信息。现在我无法找到一种方法来单击为路线绘制的线。我可以使用什么监听器?

我不想点击整个 map ,而只想点击线条。

我尝试将 click/singleclick 附加到 vector 但无济于事。

关于如何做到这一点有什么想法吗?

我的代码:

var raster = new ol.layer.Tile({
    source: new ol.source.OSM()
});

var style = {

    'LineString': new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#000',
            width: 3
        })
    }),
    'MultiLineString': new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#000',
            width: 3
        })
    })
};

var vector = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: 'kust.gpx',
        format: new ol.format.GPX()
    }),
    style: function(feature) {
        return style[feature.getGeometry().getType()];
    }
});

var map = new ol.Map({
    layers: [raster, vector],
    target: document.getElementById('map'),
    view: new ol.View({
        center: [0, 0],
        zoom: 2
    })
});

最佳答案

尝试在 map 上添加单击,然后在处理程序中检查您单击的功能。例如:

map.on('click', displayFeatureInfo); 

function displayFeatureInfo( evt ){
    //get pixel position of click event
    var pixel = evt.pixel;
    var features = [];
    //loop through all features under this pixel coordinate
    //and save them in array
    map.forEachFeatureAtPixel(pixel, function(feature, layer) {
        features.push(feature)
    });

    //the top most feature
    var target = features[0];

    //...rest of code
    target.get('customProp')


}

编辑

您可以通过向传递的对象插入额外的属性来为您的功能添加一些额外的功能。例如:

var myFeature = new ol.Feature({
        geometry: ..., 
        labelPoint: ..,
        name:...,
        customProp1: ...,
        anothercustomProp: ...
      })

关于javascript - 单击一条线并打开弹出窗口 OpenLayers 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34993498/

相关文章:

javascript - ng-click 没有在 AngularJS 中触发

javascript - 在 Weebly 中维护产品图像大小和纵横比

javascript - 如何将样式应用于 OpenLayers 3 中的修改交互?

javascript - 如何从 geoJson 加载中获取特征?

Openlayers 3打印 map div

javascript - 沿线串特征的多个文本标签

java - 通过 JSON 的多部分请求没有得到响应?

c# - 弹出窗口不会在 asp.net 中回发

javascript - jQuery 子菜单在折叠时仍然显示下拉菜单

javascript - 'aria-describedby'什么时候返回空值