How to find if a point is inside of a polygon using Racket

Viewed 796

I am working an a project that, given a specific latitude and longitude coordinate, outputs the neighborhood that the point resides in. I have the latitude and longitude coordinates that make up the boundaries of several neighborhoods within a city. I have to read the neighborhood data from a file, and also read the test-points from a file. I am using the Racket programming language.

So far I have been able to read the files and create a list of points for each neighborhood, and now I am stuck. I wanted to create a polygon for each neighborhood, and then have a method that checks to see if a point lies inside that polygon. However, I cannot figure out how to do that using Racket.

Can anyone help me find out how to solve if a point is inside that polygon, or perhaps a better way to go about solving the problem?

2 Answers

You need to start by collecting the segments of your polygon. For the point P, you need determine if the horizontal ray starting from the point P intersects the side (segment). If you count how many segments the point's horizontal ray intersects, then an odd number will be inside, and an even number will be outside.

  (define (point-in-polygon? point polygon)
    (odd? 
     (for/fold ([c 0]) ([seg polygon])
       (+ c (if (ray-cross-seg? point seg) 1 0))))))

I have a complete solution in https://github.com/StevenACoffman/lat-long-kata-racket

An alternative Ray Casting Algorithm in Racket is https://rosettacode.org/wiki/Ray-casting_algorithm#Racket as well as in 35 other programming languages.

A more detailed walkthrough is available: https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/

Related