Want more features on Pastebin? Sign Up, it's FREE!
Guest

Crossing Number Test

By: a guest on Jun 11th, 2010  |  syntax: MySQL  |  size: 2.09 KB  |  views: 1,216  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. DELIMITER $$
  2. CREATE FUNCTION trueWithin(p POINT, poly POLYGON)
  3. RETURNS INT(1) DETERMINISTIC
  4. BEGIN
  5.     DECLARE n INT DEFAULT 0;
  6.     DECLARE nr INT DEFAULT 0;
  7.     DECLARE pX DECIMAL(9,6);
  8.     DECLARE pY DECIMAL(9,6);
  9.     DECLARE ls LINESTRING;
  10.     DECLARE poly1 POINT;
  11.     DECLARE poly1X DECIMAL(9,6);
  12.     DECLARE poly1Y DECIMAL(9,6);
  13.     DECLARE poly2 POINT;
  14.     DECLARE poly2X DECIMAL(9,6);
  15.     DECLARE poly2Y DECIMAL(9,6);
  16.     DECLARE i INT DEFAULT 0;
  17.     DECLARE j INT DEFAULT 1;
  18.     DECLARE result INT(1) DEFAULT 0;
  19.     SET pX = X(p);
  20.     SET pY = Y(p);
  21.     SET ls = ExteriorRing(poly);
  22.     SET poly2 = EndPoint(ls);
  23.     SET poly2X = X(poly2);
  24.     SET poly2Y = Y(poly2);
  25.     SET n = NumPoints(ls);
  26.     WHILE i<n DO
  27.         SET poly1 = PointN(ls, (i+1));
  28.         SET poly1X = X(poly1);
  29.         SET poly1Y = Y(poly1);
  30.         IF ( ( ( (poly1X <= pX) && (pX < poly2X) ) || ( (poly2X <= pX) && (pX < poly1X) ) ) && ( pY > (poly2Y - poly1Y) * (pX - poly1X) / (poly2X - poly1X) + poly1Y ) ) THEN
  31.             SET result = !result;
  32.         END IF;
  33.         SET poly2X = poly1X;
  34.         SET poly2Y = poly1Y;
  35.         SET i = i + 1;
  36.     END WHILE;
  37.     SET nr = NumInteriorRings(poly);
  38.     WHILE j<=nr DO
  39.         SET ls = InteriorRingN(poly, j);
  40.         SET poly2 = EndPoint(ls);
  41.         SET poly2X = X(poly2);
  42.         SET poly2Y = Y(poly2);
  43.         SET n = NumPoints(ls);
  44.         SET i = 0;
  45.         WHILE i<n DO
  46.             SET poly1 = PointN(ls, (i+1));
  47.             SET poly1X = X(poly1);
  48.             SET poly1Y = Y(poly1);
  49.             IF ( ( ((poly1X <= pX) && (pX < poly2X)) || ((poly2X <= pX) && (pX < poly1X)) ) && ( pY > (poly2Y - poly1Y) * (pX - poly1X) / (poly2X - poly1X) + poly1Y ) ) THEN
  50.                 SET result = !result;
  51.             END IF;
  52.             SET poly2X = poly1X;
  53.             SET poly2Y = poly1Y;
  54.             SET i = i + 1;
  55.         END WHILE;
  56.         SET j = j + 1;
  57.     END WHILE;
  58.     RETURN result;
  59. End$$
  60. DELIMITER ;
  61.  
  62. /* usage: */
  63. SELECT trueWithin(PointFromText('POINT(-94.584799 39.100973)'), (SELECT `shape` FROM `table` WHERE `id` = 'constraint')) AS result;
clone this paste RAW Paste Data