CaptainCarl CaptainCarl - 2 years ago 402
Javascript Question

Click a line and open popup OpenLayers 3

I'm loading a GPX file into my OL3 code. Now i'd like to whole line that the GPX makes to be clickable with some extra information. Now I can't for the life of me find a way to click the line drawn for the route. What listener can I use?

I don't want to click on the whole map but just the line.

I've tried attaching click/singleclick to

to no avail.

Any ideas on how to do so?

My code:

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

var style = {

'LineString': new{
stroke: new{
color: '#000',
width: 3
'MultiLineString': new{
stroke: new{
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

Answer Source

Try adding the click on the map, and in the handler you check on wich feature you clicked. For example:

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) {

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

    // of code



You can put some extra juice in your feature by inserting extra properies to the passed object. for example:

var myFeature = new ol.Feature({
        geometry: ..., 
        labelPoint: ..,
        customProp1: ...,
        anothercustomProp: ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download