slipheed
slipheed

Reputation: 7278

Determine if a given lat/long is within the borders of the USA

How can I determine if a given lat/long is within the borders of the USA? I'd like for backend code to behave in one way if within the US and another outside of the USA. Due to requirements of the application, IP Geolocation is not an option here.

Ideally I'd like this to happen without hitting an external service.

Upvotes: 3

Views: 1511

Answers (2)

Nemo HJ Lee
Nemo HJ Lee

Reputation: 51

If you are still interested in the question, you can download shapefiles for the US.

For example,

https://www.weather.gov/gis/USStates includes all the states and territories. Thus this shapefile consists of 57 multi-polygons.

https://www.census.gov/geo/maps-data/data/cbf/cbf_nation.html has a shapefile containing one multi-polygon.

Also, there are at least one other shapefile for coastal lines (to include offshore).

With those dataset, you should make a program to determine if a (lat, lon) is located in the multi-polygon(s). That is another subject.

Upvotes: 2

Darren Engwirda
Darren Engwirda

Reputation: 7015

If you have a representation of the US as a polygon you could then use a 'point-in-polygon' algorithm, such as a crossing number test, to test whether the point lies within the polygon or not. This type of query runs in O(n) time, for a polygon with n edges.

If you want something faster, but approximate, you could do an (offline) spatial decomposition of your polygon, via something like a quadtree and determine which leaf boxes in the tree lie within the borders. The average (online) runtime to find the enclosing leaf box for a point would then be O(log(n)) for a tree with n boxes.

Hope this helps.

Upvotes: 5

Related Questions