I hit a bit of a wall here regarding using PHP & MySQL with Leaflet API. I started with PHP & MYSQL several months ago and I'm kind a newbie in that field but I'm willing to learn so please give me few pointers regarding my problem.
Question is kind a similar to that one: Creating a GeoJson in php from MySql to use with MapBox javascript API
So, I'm trying to get markers from a MySQL table using PHP and render it using Leaflet API
First, I created MySQL Table with some data:
-- phpMyAdmin SQL Dump
-- version 4.4.6
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 17, 2016 at 08:36 PM
-- Server version: 5.6.24
-- PHP Version: 5.6.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `web_gis`
--
CREATE DATABASE IF NOT EXISTS `web_gis` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `web_gis`;
-- --------------------------------------------------------
--
-- Table structure for table `baza`
--
DROP TABLE IF EXISTS `baza`;
CREATE TABLE IF NOT EXISTS `baza` (
`id` int(11) NOT NULL,
`operator` varchar(100) NOT NULL,
`lokacija` varchar(100) NOT NULL,
`x` float NOT NULL,
`y` float NOT NULL,
`prijavljen` date NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
--
-- Dumping data for table `baza`
--
INSERT INTO `baza` (`id`, `operator`, `lokacija`, `x`, `y`, `prijavljen`) VALUES
(1, 'Tele 2', 'OiV stup Hum na Sutli', 46.2135, 15.672, '2016-01-14'),
(2, 'T-Mobile HR', 'OiV stup Straža', 46.2179, 15.6999, '2016-01-03'),
(3, 'T-Mobile HR', 'Lupinjak', 46.2016, 15.7412, '2016-01-23'),
(4, 'T-Mobile HR', 'Klenovec Humski 89\\1', 46.2169, 15.7268, '2016-01-01');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `baza`
--
ALTER TABLE `baza`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `baza`
--
ALTER TABLE `baza`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Next, here is my PHP (bazneStanice_geojson.php) code which I copied from this site and adjusted a little (changed the name of base to be more precise):
https://github.com/bmcbride/PHP-Database-GeoJSON/blob/master/simple_points/mysql_points_geojson.php
<?php
/**
* Title: SQLite to GeoJSON (Requires https://github.com/phayes/geoPHP)
* Notes: Query a SQLite table or view (with a WKB GEOMETRY field) and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc. Use QGIS to OGR to convert your GIS data to SQLite.
* Author: Bryan R. McBride, GISP
* Contact: bryanmcbride.com
* GitHub: https://github.com/bmcbride/PHP-Database-GeoJSON
*/
# Connect to SQLite database
$conn = new PDO('mysql:host=localhost;dbname=web_gis','neven','gis');
# Build SQL SELECT statement and return the geometry as a GeoJSON element
$sql = 'SELECT *, x AS x, y AS y FROM baza';
# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
# Remove x and y fields from properties (optional)
unset($properties['x']);
unset($properties['y']);
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['x'],
$row['y']
)
),
'properties' => $properties
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
// print_r($geojson);
?>
And here is script block of code. (skripta_mysql.js) I must point out that I successfully rendered map and the only thing that I'm missing are the points/markers from MySQL table.
var karta = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6IjZjNmRjNzk3ZmE2MTcwOTEwMGY0MzU3YjUzOWFmNWZhIn0.Y8bhBaUMqFiPrDRW9hieoQ', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
});
bazne_stanice = new L.geoJson(null, {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {
});
},
onEachFeature: function (feature, layer) {
if (feature.properties) {
var content = '<table border="1" style="border-collapse:collapse;" cellpadding="2">' +
'<tr>' + '<th>ID</th>' + '<td>' + feature.properties.operator + '</td>' + '</tr>' +
'<tr>' + '<th>Name</th>' + '<td>' + feature.properties.lokacija + '</td>' + '</tr>' +
'<tr>' + '<th>Address</th>' + '<td>' + feature.properties.y + '</td>' + '</tr>' +
'<tr>' + '<th>Town</th>' + '<td>' + feature.properties.prijavljen + '</td>' + '</tr>' +
'<table>';
layer.bindPopup(content);}}
});
$.getJSON("bazneStanice_geojson.php", function (data) {
bazne_stanice.addData(data);
});
var map = L.map('map', {
center: [46.15796, 15.75336],
zoom: 9,
layers: [karta, bazne_stanice]
});
var baseLayers = {
"Podloga": karta
};
var overlays = {
"Bazne stanice": bazne_stanice
};
L.control.layers(baseLayers, overlays).addTo(map);
When I print variable $geojson; from php code I get array like this
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[type] => Feature
[geometry] => Array
(
[type] => Point
[coordinates] => Array
(
[0] => 46.2135
[1] => 15.672
)
)
[properties] => Array
(
[id] => 4
[operator] => Tele 2
[lokacija] => OiV stup Hum na Sutli
[prijavljen] => 2016-01-14
)
)....
To be fair I'm a bit confused. I really don't know what am I missing, followed everthing step by step but still without any luck rendering markers. Is it problem in $geojson
variable?
Should I be getting combined coordinates in [0]row? Something like this?
[coordinates] => Array
(
[0] => 46.2135, 15.672
)
============================
UPDATE:
When I try to echo
echo json_encode($geojson, JSON_NUMERIC_CHECK);
I didn't get any results and I should be getting something like this if I'm not mistaken
{ "type": "Feature", "properties": { "Operator": "T-Mobile HR", "Lokacija": "Poljana Sutlanska 8, Zagorska Sela", "Prijavljen": "21.12.2010.", "Odjavljeno": null }, "geometry": { "type": "Point", "coordinates": [ 431501.48819855711, 5110280.408429144 ] } }
I have found solution to my problem. Problem was in symbols (č,ž,š,ć,đ..) and if any given attribute had one of the symbols this code would not work:
echo json_encode($geojson, JSON_NUMERIC_CHECK);
To prevent breaking of code I had to put UTF-8 on PDO connection to check if database string is UTF-8.
Instead of this:
$conn = new PDO('mysql:host=localhost;dbname=web_gis','neven','gis');
So, I inserted something like this:
$conn = new PDO('mysql:host=localhost;dbname=web_gis;charset=utf8','neven','gis',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
and it worked like a charm.
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With