Creating a GeoJson in php from MySql to use with MapBox javascript API

吃可爱长大的小学妹 提交于 2019-11-28 20:53:24

Have a look at this: https://github.com/bmcbride/PHP-Database-GeoJSON

You are returning array instead of Json data. This is what it should look like

<?php
/*
 * Title:   MySQL Points to GeoJSON
 * Notes:   Query a MySQL table or view of points with x and y columns and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc.
 * Author:  Bryan R. McBride, GISP
 * Contact: bryanmcbride.com
 * GitHub:  https://github.com/bmcbride/PHP-Database-GeoJSON
 */

# Connect to MySQL database
$conn = new PDO('pgsql:host=localhost;dbname=mypostgisdb','myusername','mypassword');

# Build SQL SELECT statement including x and y columns
$sql = 'SELECT *, x AS x, y AS y FROM mytable';

/*
* If bbox variable is set, only return records that are within the bounding box
* bbox should be a string in the form of 'southwest_lng,southwest_lat,northeast_lng,northeast_lat'
* Leaflet: map.getBounds().pad(0.05).toBBoxString()
*/
if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
    $bbox = explode(',', $_GET['bbox']);
    $sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
}

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

You're close, and are on the right track here:

one thing I notice is that the output of my geoJson has " in the geometry array, while the one used in the MapBox example don't;

Yes, you need to make those quotes go away! Looking at your sample output you're getting a string rather than an array for the value of the 'coordinates' key in your array.

I'm not sure why this is the case based on your sample code, but something like this should work:

$geojson = array( 'type' => 'FeatureCollection', 'features' => array());

while($row = mysql_fetch_assoc($dbquery)){

  $marker = array(
    'type' => 'Feature',
    'properties' => array(
      'title' => $row['name'],
      'marker-color' => '#f00',
      'marker-size' => 'small'
    ),
    'geometry' => array(
      'type' => 'Point',
      'coordinates' => array( 
        $row['lat'],
        $row['lng']
      )
    )
  );
  array_push($geojson['features'], $marker);
}

Check this line

// The GeoJSON representing the two point features

var geoJson = ;

// Pass features and a custom factory function to the map

Try to add quotes around the php output

var geoJson = '';

$marker = array(
                   'type' => 'Feature',
                    //'features' => array(
                        //'type' => 'Feature',
                        'properties' => array(
                            'title' => $row->name,
                            'marker-color' =>'#0F8C29',
                            'marker-size' => 'small'
                            //'url' => 
                            ),
                        "geometry" => array(
                            'type' => 'Point',
                            'coordinates' => array( 
                                            $row->lng,
                                            $row->lat
                            )
                        )
                    //)
        );

    array_push($geojson['features'], $marker);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!