Im trying to perform routing with openlayers, geoserver and mysql. In order to get the start and end points, I need to be able to get a feature of the node layer (which has point features) that lies closest to an arbitrary point I click on the map. Does openlayers provide any functionality for this. If not, kindly suggest any alternative methods for achieving this.

  • What routing engine are you using? Routing data is in mySql? – user1702401 May 22 '13 at 8:09
  • I haven't made use of any routing engine. MySql does not provide any support for routing unlike pgsql. The algorithm was developed and implemented on the server side in java and the result was visualized with openlayers. – Nik May 22 '13 at 9:48
  • Thanks for the example! I'm looking for smth similar but I want to get the closest feature while I am drawing a line. Can someone help me please? – marinvirdol Aug 6 '14 at 15:38
  • Best answer is now the one of @dube posted in 2017. – F3L1X79 Feb 19 '18 at 14:36

With a bit of comparison you can:

  1. detect the point clicked
  2. find the feature closest to this point
  3. use the selectFeatureControl to programatically select this feature

see: http://jsfiddle.net/XfEmn/

(note, I use underscore.js _.min function, you could of course do this with a foor loop etc, the clue is to loop the features and get the one with the shortest distanceTo the clicked point)

  • Thanks a lot. This was exactly what I had been looking for. Thanks again for providing the perfect example. Greetings. – Nik May 22 '13 at 9:38
  • @atlefren +1 nice use of jsfiddle (interactive code) and solves rashad question clearly. – Mapperz May 22 '13 at 13:35

In case someone comes years later (like me), the solution is much easier nowadays.

ol.source.Vector has a function getClosestFeatureToCoordinate(coordinate, opt_filter) to find the closest feature to a given coordinate.

A great example can be seen in the IGC Data Example

const map = new ol.Map({...});
const vectorSource = new ol.source.Vector({...});
map.on('pointermove', function(evt) {
  var closestFeature = vectorSource.getClosestFeatureToCoordinate(evt.originalEvent);

Yes, OpenLayers has this functionality. Its called SelectFeature Control. see docs here.

you should check how the following examples work(uses: OpenLayers.Control.SelectFeature).

  1. OpenLayers Select and Highlight Feature Example
  2. OpenLayers Select Feature Example

You can get full list of examples here and apply keywords filter for select or higlight

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.