Hi, I found a stored procedure that calculates whether a point is in a polygon or outside of it. But, I'm having a little trouble adapting it to my needs.
The stored procedure is called as follows:
SET @point = PointFromText('POINT(5 5)') ;
SET @polygon = PolyFromText('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))');
SELECT myWithin(@point, @polygon) AS result;
I'd like to pull the the latitude and longitude from myPointsTable and set the @point to the result. Something like (pseudo-code):
SET @point = PointFromText('POINT( SELECT latitude, longitude
FROM `myPointsTable`
WHERE color = 'red')') ;
And then have the stored procedure iterate through those points.
Likewise, I'd like to pull the polygon from myPolygonTable. Something like (pseudo-code):
SET @polygon = PolyFromText('POLYGON((SELECT polygonPoints FROM 'myPolygonTable' WHERE town = 'Newport'))');
The stored procedure is:
DROP FUNCTION IF EXISTS myWithin;
DELIMITER $$
CREATE FUNCTION myWithin(p POINT, poly POLYGON) RETURNS INT(1) DETERMINISTIC
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE pX DECIMAL(9,6);
DECLARE pY DECIMAL(9,6);
DECLARE ls LINESTRING;
DECLARE poly1 POINT;
DECLARE poly1X DECIMAL(9,6);
DECLARE poly1Y DECIMAL(9,6);
DECLARE poly2 POINT;
DECLARE poly2X DECIMAL(9,6);
DECLARE poly2Y DECIMAL(9,6);
DECLARE i INT DEFAULT 0;
DECLARE result INT(1) DEFAULT 0;
SET pX = X(p);
SET pY = Y(p);
SET ls = ExteriorRing(poly);
SET poly2 = EndPoint(ls);
SET poly2X = X(poly2);
SET poly2Y = Y(poly2);
SET n = NumPoints(ls);
WHILE i<n DO
SET poly1 = PointN(ls, (i+1));
SET poly1X = X(poly1);
SET poly1Y = Y(poly1);
IF ( ( ( ( poly1X <= pX )
&& ( pX < poly2X ) ) || ( ( poly2X <= pX )
&& ( pX < poly1X ) ) )
&& ( pY > ( poly2Y - poly1Y ) * ( pX - poly1X ) / ( poly2X - poly1X ) + poly1Y ) ) THEN
SET result = !result;
END IF;
SET poly2X = poly1X;
SET poly2Y = poly1Y;
SET i = i + 1;
END WHILE;
RETURN result;
End
$$
DELIMITER ;
How do I use a SELECT statement in setting the variables? Is it possible? Is there a better way?
Thank you.
-Laxmidi
UPDATE:
Hi,
I've got part of the problem solved. I've figured out how to grab the latitude and longitudes.
DROP PROCEDURE IF EXISTS latlongGrabber;
DELIMITER $$
CREATE PROCEDURE latlongGrabber(IN offense_in VARCHAR(255))
BEGIN
DECLARE latitude_val VARCHAR(255);
DECLARE longitude_val VARCHAR(255);
DECLARE no_more_rows BOOLEAN;
DECLARE latlongGrabber_cur CURSOR FOR
SELECT latitude, longitude FROM myTable WHERE offense = offense_in;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;
OPEN latlongGrabber_cur;
the_loop: LOOP
FETCH latlongGrabber_cur
INTO latitude_val, longitude_val;
IF no_more_rows THEN CLOSE latlongGrabber_cur;
LEAVE the_loop;
END IF;
SELECT latitude_val, longitude_val;
END LOOP the_loop;
END
$$
DELIMITER ;
Now, I have to figure out how to combine the two functions.
-Laxmidi