How to search (predefined) locations (Latitude/Longitude) within a Rectangular, using Sql?

喜你入骨 提交于 2020-01-22 20:42:49

问题


I have the North, East, South and West values of a Rectangular location, how can I search only those locations (Latitude/Longitude) that are within the bounds of that Rectangular location?

Please note that I need to search the Locations (Latitude/Longitude) within a database. I need to find the locations in the database which are in the bounds of a given rectangular and I will draw markers for them on the map.

I am not talking about Google search, the APIs for search already support passing the rectangular bound to filter the search.

The googlemaps APIs can do this for me like:

var request = {
    bounds: myMapObject.getBounds(), // Search only within the Bound of the Map
    query: someTextToFind
};

OR

var isWithInMapsBounds = myMapObject.getBounds().contains(myLocation);

But I need to do it while getting the locations from database, I mean on Server side.

Can someone guide me in the right direction, how to achieve this functionality?

EDIT:

I want to search within database; so I need an SQL solution.


回答1:


DECLARE @Bounds AS Geography = GEOMETRY::STGeomFromText('polygon-wkt-here',0)

SELECT columns-list
FROM   table
WHERE  1 = @Bounds.STIntersects(table.point-column)

Quick note for those that are in the dark here about why you can't just compare your point location to the north/south/east/west coordinates of your bounding box:

The bounding box may not be lat/long-aligned (eg. its north/south/east/west lines may not follow lat/long axis). This will happen if you draw a planar rectangle on a Lat/Long map projection. The distortion will be more apparent the closer to the edge of the bounding box the point is, and the farther from the Equator.

The second reason to use the Geography data types is that it provides a uniform method of performing these kinds of operations for ANY polygon, not just rectangles. So now you can compare if a single point is within your box, or find all the addresses in a zipcode, all with the same piece of code.




回答2:


SQL Query

SELECT *  FROM mytable WHERE lat >= bottomlat  AND lat <= toplat AND lng >= leftlng AND lng <= rightlng

If crossing Prime Meridian or Equator you will need to modify the query

SELECT * FROM mytable WHERE lat >=bottomlat AND lat <= toplat  AND   lng >= leftLng AND lng < 0 
UNION
SELECT * FROM mytable WHERE lat >=bottomlat AND lat <= toplat  AND  lng >= 0 AND lng  <= rightLng


来源:https://stackoverflow.com/questions/15584000/how-to-search-predefined-locations-latitude-longitude-within-a-rectangular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!