OpenLayers – Finding Closest Feature to Point

openlayers-2routing

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.

Best Answer

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)