1

I am using MapboxGLJS. I retrieve the coordinates from my database and I put it in GeoJSON format on PHP which look like this:

   <?php 
            $sql = "SELECT * FROM waypoint";

            $server = "localhost";
            $username = "root";
            $password = "";
            $db = "scandrone";  
            $conn = mysqli_connect($server, $username, $password, $db);

            $result = mysqli_query($conn, $sql);

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

                    while($row = mysqli_fetch_assoc($result)){
    $marker = array(    
            'type' => 'Feature',
            'features' => array(
                'type' => 'Feature',
                "geometry" => array(
                    'type' => 'Polygon',
                    'coordinates' => array(
                         $row['longitude'],
                         $row['latitude']

                    )
                )
            )
        );
    }

        echo json_encode($marker); 
?>

And when i did an "echo json_encode($marker);" i got this

[{"type":"geojson","data":{"type":"Feature","geometry":{"type":"Polygon","coordinates":{"longitude":"2.0556640625005","latitude":"45.641158147526"}}}},{"type":"geojson","data":{"type":"Feature","geometry":{"type":"Polygon","coordinates":{"longitude":"3.3959960937499","latitude":"44.852208244354"}}}},{"type":"geojson","data":{"type":"Feature","geometry":{"type":"Polygon","coordinates":{"longitude":"1.4404296875004","latitude":"44.508493826826"}}}}]

Now I need to display this on my map. How can I do this?

3

1 Answer 1

0

A correction as you don't use from $geojson variable the "FeatureCollection" whereas you should.

<?php 
$sql = "SELECT * FROM waypoint";

$server = "localhost";
$username = "root";
$password = "";
$db = "scandrone";  
$conn = mysqli_connect($server, $username, $password, $db);

$result = mysqli_query($conn, $sql);

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

while($row = mysqli_fetch_assoc($result)) {
    $marker = array(
        'type' => 'Feature',
        'features' => array(
            'type' => 'Feature',
            "geometry" => array(
                'type' => 'Polygon',
                'coordinates' => array(
                     $row['longitude'],
                     $row['latitude']
                )
            )
        )
    );
    array_push($geojson['features'], $marker);
}

echo json_encode($geojson); 
?>

To validate your GeoJSON output, you can copy the output from your PHP script and paste it in http://geojsonlint.com (GeoJSON is a standard, don't expect things to work if you don't comply with it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.