[OpenLayers-Users] Check if the lines of an polygon are intersecting
Fernando
fnorte at gmail.com
Thu Mar 1 13:01:27 EST 2012
Hello,
I am sharing bellow with you a function that I made for a problem there I
step on it.
Using the DrawPolygon feature of OpenLayers, I had a restriction to the
polygon never be twisted. Twisted, we call when a line of a polygon cross
another line at the same polygon, creating something that appears to be
like 2 or more polygons with ends adjacents, but they are only one.
There is the .intersects() function in OpenLayers to check if two
Geometries are intersecting each other, but not apply to this case. So I
had to deconstruct the polygon in lines, to check line by line.
The function code:
/**
* Author: Fernando Norte (http://fnorte.org)
* description: check if the lines of a polygon are intersecting
* Returns: TRUE if intersects | FALSE don't
*/
// Variables are globals to debug at firebug.console
var fauxpoint, point, line, vi, vj;
function checkPolygonIntersect(){
// Get the polygon (in my case there is only one, but u can put the
'led' as parameter)
led = map.layers[1].features[0];
strng = led.geometry.toString(); // Convert to string
coord = strng.split(','); // split the coordinates
coord[0] = coord[0].substr(9); // remove the 'Polygon((' from the
1st coord
coord[coord.length-1] =
coord[coord.length-1].substr(0,coord[coord.length-1].length-2); // Remove
the '))' from the last coord
//convert to lines
for (i=0;i<coord.length;i++) {
lonlat = coord[i].split(' '); // split coord in lonlat.array
fauxpoint[i] = new OpenLayers.Geometry.Point(lonlat[0],
lonlat[1]); // convert to a point
if (i>0) {
// create an array with the 2 last points
point[0] = fauxpoint[i-1];
point[1] = fauxpoint[i];
line[i] = new OpenLayers.Geometry.LineString(point); //
create the line
}
}
var bool = false; // boolean variable
// Check every line against every line
for (var i=1;i<line.length;i++) {
for(var j=1;j<line.length;j++){
var vi = line[i].getVertices(); // get points of the I line
in an array
var vj = line[j].getVertices(); // get points of the J line
in an array
/*
* / the lines must be differents and not adjacents.
* // The end or start point of an adjacent line will be
intersect,
* // and adjacent lines never intersect in other point
than the ends.
*/
if (i!=j &&
vi[1].toString() != vj[0].toString() &&
vi[0].toString() != vj[1].toString()){
// the intersect check
if (line[i].intersects(line[j])) bool = true;
}
}
}
return bool;
}
Enjoy,
Fernando G. Norte
BHte - MG - Brasil
cel: +55 31 9119 8814
-------------------------
MSN e Gtalk # fnorte at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.osgeo.org/pipermail/openlayers-users/attachments/20120301/9342e976/attachment-0001.html
More information about the Users
mailing list