Search code examples
mysqlspatial-query

Why is this MySQL spatial query returning false rows?


I’m pulling rows based on the spatial value of column ‘latlng’, but I’m getting values outside the polygon being used by the query. For example one of the returned values is at 39.245231, -094.41976 almost 5 miles outside the polygon. Whats wrong with my query?

SELECT class, address, latitude, longitude, callsign,
               CONCAT(latitude,',',longitude) as koords,
               CONCAT(name,'<br>',address,'<br>',city,'<br>',latitude,', ',longitude) as addr,
               REPLACE(tactical,'-','') AS tactical
   FROM  poi
WHERE MBRContains(GeomFromText('POLYGON(( 39.6697989 -95.029305 , 39.6697989 -94.293333 , 38.899486 -94.293333 , 38.899486 -95.029305 , 39.6697989 -95.029305 ))'),latlng) 
      AND class = 'Sheriff'
 ORDER BY class

You can look at the map being produce at; https://net-control.us/map1Rose3.php once there click the ‘Police’ marker in the lower right to see the returned values. The map shows 4 blue flags marking the boundaries of the polygon, the red flag is the center. And two “P” markers that are outside the polygon.


Solution

  • MBRContains() is a minimum bounding rectangle function. It computes the minimum bounding rectangle of its first parameter -- draws a box around it -- then checks whether the second parameter is inside that box. It's designed to be cheap to use in computer cycles and IO, but the tradeoff is that it picks up items that are in the MBR but outside the polygon.

    Try ST_Contains() instead.