[GIS] Find closest feature

distancejsonopenlayers-2

How can I find the closest feature(coordinates) in a json file from a set lat lon using openlayers.
Currently, I get the centroid point(lat,lon) from the selected polygon feature ok, but I Would also like to return the closest feature "sid" value from the json file below.

Here is the contents of the json file:

 { "type": "FeatureCollection",
    "features": [
      {
  "type":"Feature",
    "geometry":{"type":"Point","coordinates":[146.9509,-36.069]},
      "properties":{"name":"ALBURY AIRPORT AWS","sid":72160,"rain":[0,0,0,0,0,0,0,1.2,0,0]}
},
{
  "type":"Feature",
    "geometry":{"type":"Point","coordinates":[142.0867,-34.2358]},
      "properties":{"name":"MILDURA AIRPORT","sid":76031,"rain":[0,0,0,0,0,0,0,0,0,0]}
},
{
  "type":"Feature",
    "geometry":{"type":"Point","coordinates":[142.3158,-35.0694]},
      "properties":{"name":"OUYEN (POST OFFICE)","sid":76047,"rain":[0,0,0,0,0,0,0,0,0,0]}
},
{
    "type":"Feature",
      "geometry":{"type":"Point","coordinates":[142.004,-35.1201]},
          "properties":{"name":"WALPEUP RESEARCH","sid":76064,"rain":[0,0,0,0,0,0,0,0,0,0]}
},
{
  "type":"Feature",
    "geometry":{"type":"Point","coordinates":[143.5416,-35.3766]},
      "properties":{"name":"SWAN HILL AERODROME","sid":77094,"rain":[0,0,0,0,0,0,0,0,0,0]}
}]}

Best Answer

I think that the function distance to can resolve your problem. here is the openlayers documentation : DistanceTo

And try to use this function

  function nearest_feature(pointA) {
    var minDistance = vector.features[0].geometry.distanceTo(pointA, {details: false, edge: true});
    var index =0;
    for (var i = 1; i <= vector.features.length - 1; i++) {
        var dist = vector.features[i].geometry.distanceTo(pointA, {details: false, edge: true});
        if (dist < minDistance) {
            index = i;
            minDistance = dist; 
        }
    }
     return vector.features[index].attributes['sid'];
 }

vector is your vector layer that contains your features

pointA is your centroid point that you return it should be an OpenLayers.Geometry.Point