I have a Geo-JSON Linestring, this is drawn by 800 elements in OpenLayers 4.6.5.

I'am trying to use the map.forEachFeatureAtPixel, and print a pop-up when hovering for individual elements on the linestring. However, i have trouble identifying which element in the Linestring i'm CURRENTLY hovering over.

I can extract the whole array of 800 elements from my Linestring;

map.on('pointermove', function (evt2) {
var linefeature = map.forEachFeatureAtPixel(evt2.pixel, function 
(kfeature, layer) {
return kfeature;

I have tried to experiment with forEachSegment, without any promising result:https://openlayers.org/en/latest/apidoc/module-ol_geom_LineString-LineString.html

Same for the findIndex(), i don't get any results.

How do I identify the elements in my Linestring? Or suggestions for other ways to solve this?


You would probably have get the point on the linestring corresponding to the pixel clicked, then convert each segment into a linestring to see it contains that point (using a for loop because forEachSegment doesn't pass an index):

var geometry = linefeature.getGeometry();
var point = geometry.getClosestPoint(getCoordinateFromPixel(evt2.pixel));
var coordinates = geometry.getCoordinates();
for (var element=0; element<coordinates.length-1; element++) {
  if (new.ol.geom.LineString([coordinates[element], coordinates[element+1]]).intersectsCoordinate(point){
| improve this answer | |
  • I will accept this as the answer. My solution ended up a bit easier. I still use the orEachFeatureAtPixel, and just do: 'var coordinate = evt2.coordinate;' var mygeometry = kfeature.getGeometry(); var point = mygeometry.getClosestPoint(coordinate); Works like a charm for me :) No need for the for-loop with additional complexity (as is appreas to me.. :) ) But thanks for pointing a correct solution etc:) – otk Feb 26 '19 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.