# How to check for geometry intersection (point in polygon) using OpenLayers3?

For example, I have this vector (It will be a more complicate linestring, not just a rectangle).

For a given coordinate (without clicks, just a latitude, longitude), how could I know (in an easy way, maybe collision?) if that coordinate is inside that vector?

SOLUTION

From the @JohnBarça answer, with turf library, this is working perfect:

``````var linestring1 = turf.linestring([
[4.9020, 52.3667],
[4.9030, 52.3667],
[4.9040, 52.3667],
[4.9050, 52.3667]
]);
var pt1 = turf.point([4.9040, 52.3667]);
var pt2 = turf.point([4.9060, 52.3667]);

var intersection = turf.intersect(pt1, linestring1);
if (intersection)
else

intersection = turf.intersect(pt2, linestring1);
if (intersection)
else
``````
• Which do you want OL2 or OL3? They are rather different. May 19, 2015 at 18:38
• @JohnBarça OL3 please. Thanks in advance! May 19, 2015 at 19:00
• Using turf.js is one approach I have seen, eg, stackoverflow.com/questions/29654865/… May 19, 2015 at 19:15
• @JohnBarça It's work wonderful :) Could you reply an answer and I'll set as the solution. Thanks a lot! May 19, 2015 at 19:32
• I've done some Turf demos with OL3 (including `turf.insersect` operation at thomasg77.github.io/turf-ol3 It may help for overall use of Turf May 20, 2015 at 3:09

OL3 does not support polygon intersection natively, but you can use the turf.js library, which seems to be rapidly growing in popularity and functionality.

Under the hood all geometries in turf.js are just GeoJSON, which, naturally, is supported natively in Javascript, making interop with OpenLayers, Leaflet, etc, very easy.

``````var pt = turf.point([0,0]);
var poly = turf.polygon([
[[-1, -1],
[-1, 1],
[1, 1],
[1, -1],
[-1, -1]]
]);

var intersects = turf.intersect(poly, pt);
``````

The intersect function returns a feature representing the intersection or undefined if they do not intersect.

Here is a jsFiddle showing intersection and buffering.

@JohnBarça Just a note, while turf.intersect(polygon, point) does seem to work, it was pointed out to me that turf.inside(point, polygon) is the proper function to use, for checking that a point is inside a polygon. The turf.intersect() function is intended for polygons.

See variations, according to need:

The logic here would be to first buffer the line upto the given width, and do a simple intersection query.

Both these operations require some topology and geometry operations, and can be done either in something like a Spatial Database e.g. PostGis, out even in an amazing JavaScript library called Turf.js

• Thanks @Devdatta, I was thinking that OpenLayers could check a intersection by itself :( May 19, 2015 at 18:54