# Determine if point lies within shape?

What would the best method be for determining whether an address (geocoded to a lat/long point) lies within a given shape in a GIS shapefile. Best case scenario, we are given a boolean result, that we could then apply some javascript to read yes/no results in our webapp.

We are currently using the Mapbox API for displaying the maps. I just wanted to mention that in case Mapbox has some sort of functionality in this area.

• You can probably use JavaScript Topology Suite(jsts), likely in conjunction with proj4js, to solve for a point-in-polygon. However, that doesn't really comply with your shapefile requirement ..in my opinion, the best solution will require moving beyond the shapefile. Commented Aug 13, 2015 at 17:54
• adding to what @elrobis asked, how are you using the shapefile currently? Is it only used to render tiles, or is the polygon data already in the browser (as geojson, etc.)? Also, if you have python in your environment, check out this answer
– toms
Commented Aug 13, 2015 at 18:09
• Thanks guys, I would be happy to move away from using the shape file completely. I'm just looking for a solution that would be best for returning a Boolean result for an address. And yes, the shape files are only being used to render files via Mapbox. Commented Aug 13, 2015 at 19:40
• You could pass the geometries to ESRI's public geometry service and do an intersect: tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/… Commented Oct 6, 2015 at 14:41

If your shapefile can be converted to GeoJSON, in other words you were able to create a proper Leaflet layer out of it in Mapbox, you can use TurfJS's Inside operator like here:

http://turfjs.org/static/docs/module-turf_inside.html

If you really don't want any dependency you can go back to secondary school calc. :) My algorithm is like this:

1. Iterate over the polygon's sides in one direction taking the 2 endpoint of the given polygon side.
2. Let's call the endpoints p0(x0,y0) and p1(x1,y1). Your address point to check is P(x,y)
3. Calculate signed distance from the line defined by the 2 polygon points:

d=((y0-y1)x+(x1-x0)y+(x0y1-x1y0))/sqrt((x1-x0)^2+(y1-y0)^2) (reasoning here)

1. If the point IS WITHIN your polygons then the distances calculated from the polygon sides will have the same sign (depending on the direction of the rings all positive or all negative)
2. If your polygon has holes you need to iterate over all the rings inside and your point has to be NOT WITHIN the inside rings but WITHIN the outer ring.

Hope this helps. This will not work for erroneous polygons like "bowties" (sides crossing themselves).

I'm sure there can be tons of other algo's for this tasks. This just came off the top of my head as something that can be coded simply in JS.