PHP & MySQL 和 Leaflet API

标签 php mysql leaflet geojson

关于将 PHP 和 MySQL 与 Leaflet API 结合使用,我在这里遇到了一些障碍。几个月前我开始使用 PHP 和 MYSQL,我是该领域的新手,但我愿意学习,所以请就我的问题给我一些建议。

问题有点类似于那个: Creating a GeoJson in php from MySql to use with MapBox javascript API

因此,我尝试使用 PHP 从 MySQL 表中获取标记并使用 Leaflet API 呈现它

首先,我用一些数据创建了 MySQL 表:

-- 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 */;

接下来,这是我的 PHP (bazneStanice_geojson.php) 代码,我从该站点复制并稍作调整(更改了 base 的名称以便更准确):

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);
?>

这是脚本代码块。 (skripta_mysql.js) 我必须指出,我成功渲染了 map ,唯一缺少的是 MySQL 表中的点/标记。

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 &copy; <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);

当我打印变量 $geojson 时;从 php 代码我得到这样的数组

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
                        )

                )....

公平地说,我有点困惑。我真的不知道我错过了什么,一步一步地进行,但仍然没有任何运气渲染标记。 $geojson 变量有问题吗?

我应该在 [0] 行中获取组合坐标吗? 是这样的吗?

 [coordinates] => Array
(
 [0] => 46.2135, 15.672
)

============================

更新:

当我尝试回应时

echo json_encode($geojson, JSON_NUMERIC_CHECK); 

我没有得到任何结果 如果我没记错的话我应该得到这样的东西

{ "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 ] } }

最佳答案

我找到了解决问题的方法。问题出在符号 (č,ž,š,ć,đ..) 中,如果任何给定属性具有其中一个符号,则此代码将不起作用:

echo json_encode($geojson, JSON_NUMERIC_CHECK);

为了防止破坏代码,我必须将 UTF-8 放在 PDO 连接上以检查数据库字符串是否为 UTF-8。

取而代之的是:

$conn = new PDO('mysql:host=localhost;dbname=web_gis','neven','gis');

所以,我插入了这样的东西:

$conn = new PDO('mysql:host=localhost;dbname=web_gis;charset=utf8','neven','gis',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

它就像一个魅力。

希望对您有所帮助!

关于PHP & MySQL 和 Leaflet API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843393/

相关文章:

mysql - 每周表的正确结构和索引

传单路由机 - 选项的使用

javascript - 如何使用 JavaScript 生成的 HTML 进行 jQuery 操作?

javascript - 使用 react-leaflet 时缺少 Leaflet Map Tiles

php - 如何使用id或邮箱登录

javascript - Google reCaptcha - 如何获得 g-recaptcha-response - 没有 FORM TAG

php - Laravel 关系的外键等价物

PHP 和 SQL 哈希帮助 : What am I doing wrong?

mysql - 查找过去 24 小时内具有日期字段的记录

mysql - 想要编写基于未出现在另一个表中的表中选择的查询