I have a MySQL database that contains a large number of polygons, one for each district on a map. They are all quite complicated and it’s unrealistic to simply load them all at once. I’ve looked into using MarkerManager for Google Maps API v3 and this seems to be working as intended. However I’m not sure how to best go about querying my database for polygons that are in the viewport.
I’m thinking that it would be best to store the center of each polygon in a separate column as a simple lat,lng pair so that a query could be run on that – and then return the full polygon.
What is the best way to go about this?
SELECT * FROM polygons WHERE [the center of each polygon is within the bounds of the viewport]
Is this even possible? Am I going about this the wrong way?
And additionally, is there a simple script I can run on my data to return the center of each polygon?
The format of the query will depend on the database schema, of course. If you’d like to fetch polygon data for polygons with center points inside the current viewport, you could try this:
The query considers the center point to be the center of the polygon’s rectangular bounding box, which could be somewhat different from the “weighted” center for peculiarly shaped polygons. The coordinates of the bounding box, as returned by calling getNorthEast() and getSouthWest() on a LatLngBounds object, are represented by the pseudo-variables “$viewport_lat_southwest”, etc.; “lat_northeast” etc. represent columns in the database table.
The query can be fairly easily adapted to select only polygons having all or any of their bounding box within the viewport by comparing only the “near” coordinate (for all) or the “far” coordinate (for any) of the polygon to the viewport coordinate.
If you have separate records for the individual points in each polygon, you could select them like this:
That would select polygons with any points in the viewport. To find polygons with all points in the viewport, you could try this:
That query also demonstrates a strategy for calculating the bounding box from a set of points: