问题
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