Need to calculate latitude longitude from postal code database when location has multiple codes

梦想的初衷 提交于 2019-12-23 03:35:18

问题


How do I calculate the lat/lon for a given location from a postal code database when there are multiple codes for a given location? For example, New York City has 165 postal codes.

SQL example (There is also a Latitude and Longitude column in the table):

SELECT City, [State], StateAbbr, Country, COUNT(*) AS ctCodes
FROM PostalCodes
WHERE (City = 'New York City' AND StateAbbr = 'NY')
GROUP BY City, [State], StateAbbr, Country
ORDER BY ctCodes DESC

Returns:

City          | State    | StateAbbr | Country | ctCodes
New York City | New York | NY        | US      | 165

I considered calculating the lat/lon of the center of the bounds, which gets a little complicated. Consider this query:

SELECT City, [State], StateAbbr, Country, 
    COUNT(*) AS ctCodes, 
    MIN(Latitude) AS south, 
    MAX(Latitude) AS north,
    MIN(Longitude) AS west,
    MAX(Longitude) AS east
FROM PostalCodes
WHERE (City = 'New York City' AND StateAbbr = 'NY')
GROUP BY City, [State], StateAbbr, Country
ORDER BY ctCodes DESC

Returns:

City          | State    | StateAbbr | Country | ctCodes | south  |  north |   west  |  east
New York City | New York | NY        | US      | 165     |40.69640|40.86620|-74.02530|-73.67310

Getting the bounding rectangle works for north america, but it obviously wouldn't work for the southern hemisphere or east of the Prime Meridian. Am I going down the right road? Is there a better way to do this? Any help would be much appreciated.


回答1:


Computing a bounding box or averaging the lat-long coordinates will more-or-less work for locations that are not on the 180th meridian; that is, is pretty much anywhere but in Fiji.

An approach that will work anywhere on the globe, Fiji included, is converting the coordinates into points on a 3D sphere, computing the midpoint, and projecting the midpoint to the surface of the sphere. This of course will be computationally more expensive.

First convert each lat-lng pair into 3D cartesian coordinates:

x = cos(lat)*cos(lng)
y = cos(lat)*sin(lng)
z = sin(lat)

Then compute the midpoint by averaging the coordinates, giving (x', y', z'). Now convert this back into lat-lng, and you'll have the coordinates for the center point:

  r  = sqrt(x'² + y'² + z'²)
lat' = asin(z'/r)
lng' = atan2(y', x')


来源:https://stackoverflow.com/questions/19235623/need-to-calculate-latitude-longitude-from-postal-code-database-when-location-has

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