[GIS] Problem with loading GeoJSON file in OpenLayers generated by PHP

geojsonjsonopenlayersopenlayers-2PHP

I'm trying to read some geo-data from PostGIS database using PHP, creating a GeoJSON file and showing it on a base map using OpenLayers.

The PHP code works just fine. The generated data in GeoJSON format is valid (I checked it with jsonlint). When I load the page, the developer tools shows no errors, but also doesn't load any data on the map.

I have just started learning OpenLayers and don't know much about it but saw some examples for this and tried to do the same.

Am I doing something wrong in the Openlayers code?

The code is:

var map = new OpenLayers.Map({
    div: "map",
    layers: [
        new OpenLayers.Layer.WMS(
            "WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0",
            {layers: "basic"}
        ),
        new OpenLayers.Layer.Vector("GJ", {
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "gj/DB2GeoJson.php",
                format: new OpenLayers.Format.GeoJSON({
                    extractStyles: true, 
                    extractAttributes: true,
                    maxDepth: 2
                })
            })
        })
    ],
    center: new OpenLayers.LonLat(-112.169, 36.099),
    zoom: 11
});

and the GeoJson file generated is:

{
"type": "FeatureCollection",
"features": [{
    "type": "feature",
    "id": "97",
    "geometry": null,
    "properties": {
        "popn_total": ["97"],
        "boroname": ["Staten Island"]
    }
}, {
    "type": "feature",
    "id": "66",
    "geometry": null,
    "properties": {
        "popn_total": ["66"],
        "boroname": ["Staten Island"]
    }
}, {
    "geometry": ["{\"type\":\"MultiPolygon\",\"coordinates\":[[[[578620.717363209,4495974.81786636],[578535.357633272,4495915.80999248],[578524.626146389,4495908.44992811],[578475.151658836,4495981.94016235],[578550.53822566,4496033.27562186],[578571.6880873,4496047.75223892],[578620.717363209,4495974.81786636]]]]}"]
}]

}

Best Answer

Your generated GeoJSON is valid JSON, no problem. But, it's not valid GeoJson, as you can see here: http://geojsonlint.com/

The problem seems to be that the features-array in your featurecollection contains three features, two with geometry:none and one with just geometry (which is also string-encoded).

So, in short: Your OpenLayers-code seems fine, the trouble is your PHP-code that generates the GeoJSON.