问题
I have a bus point in Lat/long (geography). I want to check where my bus point (lat/long) lies in a region. My region is a set of lat/long points. I have lat/long of a region (Outline of the lat/longs which makes a region) in geography form. Now I have one point lat/long and I want to identify if that point lies inside my region. How can I do that? 4000 points make an outline of a region and one point is to check if that exist in that region or not. How will I check that?
I think I can use STContains or STintersect but I don't know the exact syntax.
SELECT
Region.BlockID, Bus_Route.geography
FROM
Bus_Route, Region
WHERE
Region.points.STContains(Bus_Route.geography) = 1
回答1:
I used the code that I wrote for you (Storing 'Point' column from ShapeFile) as a starting point to get a table of points. From there:
select geography::STPolyFromText(
'POLYGON((' +
stuff((
select ',' + cast(g.STPointN(t.i).Long as varchar(10)) + ' ' + cast(g.STPointN(t.i).Lat as varchar(10))
from [a]
cross join tally as [t]
where t.i <= g.STNumPoints()
order by i
for xml path('')
), 1, 1, '') + '))'
, 4326)
This code assumes a couple of things. First: that your points are ordered as you would go around the boundary of the region. This matters. Think about a connect-the-dots puzzle. In order to get the right picture, you have to do them in the right order. Secondly, related to the first, they have to be in the correct orientation. Polygons follow the left-hand rule. That is, if you were walking the points in order, you're defining the region that is at your left side. So, if you specify the points in reverse order, you get everything but your region! You'll know this right away since before SQL 2012, you're limited to having regions that are fully contained in a hemisphere.
But now I have to ask: given the question that you asked before (that I linked to above), are you receiving shapefiles with polygons in them? If so, store that and save yourself the headache of reconstructing it.
来源:https://stackoverflow.com/questions/13484636/stcontains-on-geography-column