Detecting a certain Latitude / Longitude is in a US State
I know that most开发者_运维百科 people will view this question and point me to Google Geocode - but I'm looking for a mathematical formula that allows someone to take a Lat/Lng point and see if its inside a US state (or a bounding box). Is there a way via PHP, that I can do a calculation to see if a point is in a certain Box (such as California)?
Well, there's no formula that'll tell you anything about what states is where (it would have totally been a spoiler as to the outcome of the US-Mexico war if there was!) So you'll need to get that data from somewhere.
This then turns into one of two problems, depending on the degree of accuracy you want.
If you have details of a bounding box that is rectangular when shown on a Mercator or similar projection (that is, it has degrees of latitude for north and south, and of longitude for east and west), then the formula is simply:
inBox = latitude <= north && latitude >= south && longitude <= west && longitude >= east
If you have more detail, and have a series of points that defines the border of the state (obviously, the more points, the more precision) then it becomes a variant of the point-in-polygon problem, with a guarantee of only involving simple polygons (no US state has a border that crosses itself, nor completely surrounds that used in this C code. It's possible that there would be edge cases affected by the fact that this is a 2D-plane algorithm rather than a spherical one, but I imagine you'd need to have some pretty precise data on the boundaries of the states for the imprecision from the algorithm to be greater than that caused by the data.
The simplest way I would think is using bound box for each state, that can be found from Flicker Geo API, an example for CA- https://www.flickr.com/places/info/2347563
精彩评论