I need a free(open-source) solution that given the lat/lng can return the closet city/state or zip. mysql is not an option, a small lightweight database would be the best if possible.
Updates: No web services, with 50 million impressions a day even the smallest addon hurts so adding a service request would kill response time. I would prefer not to add more than 200 milliseconds on to the request.
I have the database, lat/lon/zip/city/state in csv it’s just how to store and more importantly how to retrieve it the quickest.
Brute force: pre-load all of your data into an array. Calculate the distance between your current point and each point in the array (there’s a method to do this calculation that uses linear algebra instead of trig functions, but I don’t recall what it is offhand) to find the closest point.
Please read this before down-voting: there are ways to speed up a brute force search like this, but I’ve found that they’re usually not worth the trouble. Not only have I used this approach before to find nearest zip from latitude/longitude, I’ve used it in a Windows Mobile application (where the processing power is not exactly overwhelming) and still achieved sub-second search times. As long as you avoid the use of trig functions, this is not an expensive process.
Update: you can speed up the search time by apportioning your zip data into sub-regions (quadrants, for example, like northwest, southeast etc.) and saving the region ID with each data point. In the search, then, you first determine what region your current location is in, and compare only to those data points.
To avoid boundary errors (like when your current location is near the edge of its region but is actually closest to a zip in the neighboring region), your regions should overlap to some extent. This means some of your zip records will be duplicated, so your overall dataset will be a bit larger.