1

I am making a map using layers stored in a PostgreSQL (PostGIS) database. I am using GeoServer to successfully load layers with Leaflet in WFS format, but I wonder how to make SQL request on it through my JavaScript code.

How can I do that ? Or more generally, how can I can simply connect to a PG database within a JS script ?

2 Answers 2

1

You can't send SQL directly but GeoServer allows you to apply a filter to your GetFeature request as either an OGC filter (as all WFS do) or as a CQL filter.

GeoServer then translates as much as possible of that filter to SQL to pass to PostGIS and handles the rest seamlessly for you.

5
  • I don't really understand your answer but I gonna have a look. From what I've read so far, process to connect to a PG database may look like this : const { Client } = require('pg') const client = new Client({ host: 'my.database-server.com', port: 5334, user: 'database-user', password: 'secretpassword!!', }) I tried but I got error at first line for require('pg').
    – RG70
    Commented Feb 28, 2020 at 14:57
  • You shouldn't connect to PG directly, just add the filter to the WFS getFeature request
    – Ian Turton
    Commented Feb 28, 2020 at 15:16
  • Alright, but with your method, how can you iterate through lines of a PG table ? In my case, I would need to get each property of the features in a JS loop...
    – RG70
    Commented Feb 28, 2020 at 15:22
  • Your filter is sent to PG to restrict which features are returned no need to iterate anything
    – Ian Turton
    Commented Feb 28, 2020 at 15:30
  • Yes but the features are returned into a map format. I would just like to get the features as a JS matrix.
    – RG70
    Commented Feb 29, 2020 at 16:52
0

You can't connect to server-side database via JavaScript. You should either use Geoserver to handle your request, or use another server-side language to handle it through webservices, such as Java Spring boot, php, Node.js, etc.

For example, if you want to search an area, you can write a webservice on the server-side and call it by JavaScript, and then handle the returned data to be shown on the map as tables for example.

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.