score:5

Accepted answer

Leaflet would need some tweaking if you wish to do this. It leaves the handling of mouseclicks to the browser and therefore does not need logic for determining if a point lies inside a polygon.

I am not very knowledgeable about d3 but it's not glaringly obvious to me how it'd do this out of the box. Looking at the polygon code, I do find a clipping algorithm and intersection of infinite lines.

If you add a third library, however, this should be rather simple. The OpenLayers Geometry library can determine if a point lies inside a polygon.

EDIT: I got this to work, see also http://jsfiddle.net/VaY3E/4/

var parser = new OpenLayers.Format.GeoJSON();
var vectors = parser.read(statesData);
var lat = 36;
var lon = -96;
var point = new OpenLayers.Geometry.Point(lon, lat);
for( var i = 0; i< vectors.length; i++ ){
    if(vectors[i].geometry.intersects(point)){
       alert(vectors[i].attributes['name']);
    }
}

Or you could use https://github.com/maxogden/geojson-js-utils , a bit more specific library. It looks like it knows how to read GeoJSON and it has a method gju.pointInPolygon. I've not tested it though.


Related Query