Get zip code from latitude/longitude

自作多情 提交于 2019-12-10 22:19:58

问题


I have a control that allows a user to either enter a zip code or open up google maps in an iframe and click on the map to pick a location. I currently have this all working and the iframe will send the lat/lon from the click event back to the parent.

I also have a db table set up with lat/lon fields mapped to zip codes.

However, the lat/lon combination will most likely never exactly match the entry I have in the db. So, I'm looking for the best way to match the closest zip code.

Because the user has the ability to manually enter the zip code, I'm not totally worried about precision(i.e. if a user clicks on a border between zip codes), but I would like it to be close as possible. I only need to worry about US locations for now.

My current idea for a solution is to come up with some tolerance(.2?) and query the db for the lat/long +- the tolerance. Then pick the closest match from the result set.

I'd love to hear from someone who has done this before or has a better solution than the one I proposed. I'm not interested in using a service as I have all the data I need.

One concern I have with my proposed solution is figuring out what a good tolerance would be. This project is targeted for rural areas and I'm not sure how spread out the lat/lon entries for these areas could be.

Edit: Here is my table structure: zip5 | city | state | lat | lon | county

zip5 is the primary key


回答1:


The canonical solution to this problem uses R-trees.




回答2:


One minute of Latitude (ie 1/60 degree) = 1 n.m., or about 6,000 feet. Therefore 5 min. Latitude = about 30,000 feet = about 6 statute miles.

Longitude narrows towards the poles, but if we take the continental US as being about 36 degrees North, give or take (a fair bit I agree, but an approximation should be suficient for this application), then one minute of Longitude ~ 1 n.m. * cos 36 ~ 6,000 * 0.81 = 4,850 feet.

Since Zip codes (or at least the first set of 5 digits) represent post offices, which in rural areas are likely 20-30 miles apart, you could do worse than to use a Lat-Long grid of about 1/2 that, or say 10 min. Latitude x 12 min. Longitude. Those are conveniently 1/6 degree and 1/5 degree respectively.




回答3:


You might want to ditch your own database lookup and use a webservice that already does this, such as GeoNames. See the SO question Get zip code from latitude, longitude? for more info. Looks like it already does what you're trying to do, but without all the calculations and tolerances.



来源:https://stackoverflow.com/questions/15304198/get-zip-code-from-latitude-longitude

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!