Saturday, 23 June 2018

openlayers - 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?


enter image description here





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)
alert('found pt1')
else
alert('not found pt1')

intersection = turf.intersect(pt2, linestring1);
if (intersection)

alert('found pt2')
else
alert('not found pt2')

Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...