This a very basic question, but I don´t quite know where to start

I have a postgis table with aproximately 15.000 points hosted on CartoDB

And I'm developing an application that should let the user navigate a map, and show the points that are inside that area, with several filter applied

I was thinking about building a query like this to pass to the web service

select * from my_table 
      'POLYGON((-71.177 42.390,-71.1776 42.3903, -71.1776 42.3903,-71.17758 42.3903))'
  ) and
  [more filter conditions]

I just need to know the four points of the view port from leaflet, and update it everytime the user moves or zooms...

I guess this it just what the map view on cartoDB does...

Can anybody give me a hint on how to achieve it, or at least tell me if my approach is completely wrong.

Thanks a lot

1 Answer 1


You're on the right track. I think you may want to use ST_Within rather than ST_Contains; at the very least, you'll want to reverse the order of your arguments to ST_Contains. In the example you provided, you're asking if the_geom contains the POLYGON you specified.

To get the bounding box in Leaflet, you could try something like:

var b = map.getBounds(); // An instance of L.LatLngBounds
var s = 'POLYGON((';

// Build up a POLYGON WKT string
[b.getNorthWest(), b.getNorthEast(), b.getSouthEast(), b.getSouthWest(), b.getNorthWest()].map(function (ll) {
    s += ll.lng + ' ' + ll.lat + ',';
// Strip last comma and space
s = s.substring(0, s.length - 2)

// Don't forget the final '))'
s += '))';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.