For example, in my database I've some points with geographic coordinates. I want to display them on Leaflet JS layer. Which instruments should I use? Maybe there is some API...
2 Answers
In order to get data from a database into a web browser, you need to use a server-side script. This can be tricky to do because you need to be aware of vulnerabilities, like SQL injection. Some best practice important things to note is that you should use parameterised queries and ensure that your database user is unprivileged, having only read access to the tables that you want being public.
The easy way to get API access to a database is to use a bit of software like GeoServer, but that is a very big application to use for potentially small problem.
Another method would be to have a server-side script dump the data out into a GeoJSON file periodically, depending on how often your data changes, this could be hourly, daily, weekly. keep in mind that your website might not function while the file is writing.
Another method is to use PHP or Python as a CGI script to build your own API.
Examples:
- PHP PostGIS Api: https://gist.github.com/bmcbride/1913855
- GeoServer: http://geoserver.org/display/GEOS/Welcome
- WFS GeoJSON: http://docs.geoserver.org/latest/en/user/services/wfs/outputformats.html
- ogr2ogr - read postgis write geojson: http://www.gdal.org/ogr2ogr.html use CRON: https://help.ubuntu.com/community/CronHowto
Once you have GeoJSON, whether dynamic or static, you can load it very easily using Leaflet: http://leafletjs.com/examples/geojson.html.
-
1Thanks for answer. I incline to use GeoJSON. Now I want to use CSV file instead of Postgis, convert it to geoJSON and then display data with Leaflet. Commented Nov 4, 2013 at 10:45
-
1use then ogr2ogr reading csv to convert easily to geoJSON Commented Nov 4, 2013 at 10:52
-
1If your data is too big and takes too long to load as JSON, take a look at TopoJSON. github.com/mbostock/topojson Commented Dec 16, 2013 at 5:02