Verify a lat/long coordinate is in a SQL spatial table on geography column

1.6k views Asked by At

We have a spatial table (dbo.Map) with eleven polygons representing eleven regions. This table has unique IDs, names, and other meta data associated with it, as well as a geography data-type column called geo. We also have a separate table (dbo.points) with a list of points with their lat/longs that are in the regions defined by the first table. The two tables don't have anything to join them on, unless we are able to join a lat/long to a geography column. How can we return a list of all the points in a given region?

1

There are 1 answers

0
Ben Thul On

Here's how I'd do it:

First, I have to infer your schema. I'll choose something like this:

create table dbo.Map (
   MapID int identity not null,
   geo geography not null
);

create table dbo.Points (
   PointID int identity not null,
   Latitude decimal(9, 7),
   Longitude decimal(10, 7),
   geo as geography::Point(Latitude, Longitude, 4236) persisted
);

Next, the select:

select PointID, MapID
from dbo.Points as p
left join dbo.Map as m
   on p.geo.STIntersects(m.geo) = 1

You'd probably want to add some sort of where clause, but that's the bare bones "how do I find which region my point is in?".

Also note that the points table has a persisted computed column that is a geography instance that represents the point given by the Longitude and Latitude columns. This is good for a couple of reasons:

  1. You can't put junk (e.g. abs(Latitude) > 90) data into Latitude and Longitude.
  2. You get the geography instance stored in-row so you don't have to calculate it every time