OpenLayers - How to get getClosestFeaturetoCoordinate to work or similar

646 views
Skip to first unread message

Michael S

unread,
May 23, 2016, 4:41:33 PM5/23/16
to Tethys Platform
I'm hoping that Alan will have some good insights for this.

I
 am working on an app that uses openlayers and I want it to select the feature closest to a mouse click. I know there is a getClosetFeatureToCoordinate function but I didn't find specific examples using it. Have any of you used it or have you done anything similar to what the link below shows with the current openlayers 3 library? If so I would appreciate some help and directions with that.

Thanks,
Michael
Message has been deleted

alansnow21

unread,
May 23, 2016, 5:39:23 PM5/23/16
to Tethys Platform
That is a difficult question. If your vector layers are selectable:

m_select_interaction = TETHYS_MAP_VIEW.getSelectInteraction();

//to make sure that you always get something on click

var map = TETHYS_MAP_VIEW.getMap();

map.on("click", function(evt) {

    var feature_collection = m_select_interaction.getFeatures();

    if(feature_collection.getArray().length <=0) {

        this.getLayers().forEach(function(layer, i) {

            var source = layer.getSource()

            if (source instanceof ol.source.Vector) {

                var closest_feature = source.getClosestFeatureToCoordinate(evt.coordinate);

                feature_collection.push(closest_feature);

            }

        });

    }

});


swainn

unread,
May 24, 2016, 11:34:38 AM5/24/16
to Tethys Platform
If you look at the version number of the OpenLayers library being used in the JSFiddle, you will see that it is 2.13.1. Tethys includes OpenLayers 3.10.1. Version 2 and version 3 are very different, so please be sure you are using the correct documentation: http://openlayers.org/en/v3.10.1/doc/ and always search "OpenLayers 3" when you are looking for solutions. You will find a lot of solutions for the old OpenLayers 2 library. If you have a vector layer loaded in OpenLayers then you could do something like Alan suggests. If it is a GeoServer layer, you can use a clever combination of ECQL filters:


For example, the way the feature selection feature of Tethys works is it buffers a box around the point the users selected and then uses the BBOX filter to select only points that fall in that box.
Reply all
Reply to author
Forward
0 new messages