1

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.

4

1 回答 1

2

计算边界框或平均经纬度坐标或多或​​少适用于不在180 经线的位置;也就是说,除了斐济,几乎在任何地方。

一种适用于全球任何地方(包括斐济)的方法是将坐标转换为 3D 球体上的点,计算中点并将中点投影到球体表面。这当然会在计算上更加昂贵。

首先将每个 lat-lng 对转换为 3D 笛卡尔坐标:

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

然后通过平均坐标计算中点,给出(x', y', z'). 现在将其转换回 lat-lng,您将获得中心点的坐标:

  r  = sqrt(x'² + y'² + z'²)
lat' = asin(z'/r)
lng' = atan2(y', x')
于 2013-10-08T00:06:02.877 回答