Leaflet tutorial with input from MySQL database


Hi,

I would like to present to you a very nice alternative to Google Maps, if you are not confortable with the credit card policy.
I had a project in which I needed to store latitude and longitude of the user when he submits the form with other input data (some questions involving electric security). When the user submits the data, the coordinates are sent to the MySQL database. For my project it was very important that the submission is bound to the location. I developed a table in which the data could be displayed from the db, but I need something more visual, something that could help me make a quick analysis of the frequency of problems in a restricted area.
First option that came into my head was of course Google Maps, because it is easy to implement, huge documentation, but at that time everyone was scared of the changes that they did with their packages. To be sincere I did not know what to choose between them and how to interpret the prices. So I figured I should try and search for something open-source, free, etc, like the utopian dream, but after a few searched I came onto Open Street Maps, which is an open-source map support platform. You can use this platform as long as you leave their credit icon right below their map (but it's a tiny little sign so it's not a big problem). Their map support is pretty updated and very visually friendly. Ok,ok we have the map support, but it has no controls? no objects?no layers? no pin-points? welllll that's a problem which can be solved with Leaflet js. This library lets you use layers, pin-points and other objects on this map support as long as you credit them too for their work.
This is how it looks like right below your map object.

Problem was that the format accepted by the script was json, but I needed to use as source my MySQL db, so I established a connection with the database, selected all the data that I needed, and fetched it inside an array. After the fetch I encoded the array into a json format. Using "for" I looped through the whole array and displayed them on the map .

To give you an idea of how the code looks:
PHP:
*connection with the database*
*sql_query to select data from db*
*error handling for the query execution
*while the fetch is active we throw every item into an array*

JS:
*define a js variable to encode php variable into json*
*loop trough the json array and add its data to the corresponding pin-point on the map.

If you don't know how to set up pins and install leaflet go to their site and they have there a very well documented and structured tutorial.
After I received the data from the database for every pin I made it work like a link that would query the database to go directly into the request in a reporting page with all the informations structured in a detailed way like a data input form.



Comments