将SQL Server GEOGRAPHY拉到多边形

时间:2016-06-25 17:13:15

标签: sql sql-server json sqlgeography

我有这个查询

SELECT 
    ' {"location":"'+ G.ZCTA5CE10 +', ' + INTPTLON10 + ', ' + INTPTLAT10 + '",'+
               '"polygon":' +
                replace(replace(replace(replace(replace(replace(replace(G.geom.ToString(), 'POLYGON ((', '[{"lng":'), '))', '}]'), ', ', '},{"lng":'), ' ', ',"lat":'), ')', ''), '(', ''), 'MULTI', '') +
                '}'
FROM REF_ZIP_GEOG G WITH(INDEX([geog_sidx]))
WHERE G.geom.STDistance(geography::STPointFromText('POINT(-81.3225 32.113)', 4326))<= 40234;  --40.234 KM ~ 25 Miles

此查询的目的是将GEOGRAPHY多边形“字符串化”为谷歌地图。 POLYGONS工作得很好。但是,如果POLYGON是MULTI-POLYGON,我在使用JSON时遇到问题。结果是Google错误的JSON。

有没有人使用过MULTI POLYGONS,您是否可以推荐任何改变我的SQL语句的方法来正确使用它?

感谢。

1 个答案:

答案 0 :(得分:1)

虽然你需要翻译成你的替换......

Ignore "MULTIPOLYGON"s and split on ")), ((" and handle each as you would a polygon.

但是,我用来实现这个的最简单,最快的方法(主要是在JS中):

get the geography.STAsText() from sql into some functional language
foreach multi
    replace "MULTIPOLYGON" with "" (nothing)
    split on ")), (("
    foreach poly
        replace "POLYGON" with ""
        split on "), ("
        foreach coordset
            replace "[((]" and "[))]" with ""
            split on ","
            foreach point
                trim and split on " "
                lat = coord[1]
                lng = coord[0]