Posts Tagged ‘Google Maps API V3’

Google Maps API v3: How to query the current viewport?

Sunday, December 18th, 2011

Basically…the business logic is like this:

You need to get the boundaries from the map object and then pass these as parameters via AJAX to the SQL query which fetches the records, e.g minLat/maxLat & minLng/maxLng … these go into the WHERE condition. This will “cut out a rectangle” from your geo-data. You might adjust these values by 5-10% – so that points very close to the boundaries will not be painted to the map (that’s just a cosmetic fix).

function loadViewport() {
    var b = map.getBounds();
    $.minX = b.getSouthWest().lat();
    $.maxX = b.getNorthEast().lat();
    $.minY = b.getNorthEast().lng();
    $.maxY = b.getSouthWest().lng();
    $.url = "data.php?minX="+$.minX+
       success: parseJSON
function parseJSON(json){
   /* adding markers & further processing happens here */

The WHERE condition of the SQL would be something like that:

   (latitude BETWEEN ".$minX." AND ".$maxX.") 
   (longitude BETWEEN ".$maxY." AND ".$minY.")

Of course the columns in the table need to be of data-type float – else this won’t work for sure.