Search code examples
javascriptnode.jsjsonopenlayersgeojson

GEOjson not displaying in my map openlayers


I want to display geojson data in my map openLayers but my data didn't show and the map doesn't even display. I work with openLayers 5. I have an api (in node.js) which allows to extract the data in my database. I have a file (script.js) which allows to display the map, recover the data sent by the api and display the data on the map.

In script.js :

I create a new vectorLayer which contain the style of the geojson :

 var foncier2 = new VectorLayer({
source:source,
style: function (feature, res) {
  property = feature.get("nature");
  return new  Style({
    stroke: new Stroke({
      color: [40, 40, 40, 1],
      width: 0.3
    }),
    fill: new Fill({
      color: couleur(property)
    })
  })
},});

I request on my API to recover the data with the help of a callback :

`
function loadJSON(callback) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            console.log(this.responseText);
            callback(this.responseText);
          }
        };
        xhr.open("GET", "adressIP:port/endpoint", true);
        // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(null);
      }`

Then I create a function which transform the data into json then into GEOjson :

   var myData = JSON.parse(data);

var geojsonObject = {
 "type": "FeatureCollection",
 "crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
 "features": [
   {
     "type": "Feature",
     "geometry": {
       "type": "Polygon",
       "coordinates":myData[2].geom
     }
   }
 ]};

Finally i display the data :

foncier2.getSource().clear();
foncier2.getSource().addFeatures(foncier2.getSource().getFormat().readFeatures(geojsonObject, {
  dataProjection: 'EPSG:4326',
  defaultFeatureProjection: 'EPSG:3857',
}));
foncier2.getSource().refresh();
foncier2.getSource().changed();
map.getView().fit(foncier2.getSource().getExtent());

But
nothing displays on my map and I don't have error in my console log.

Thank you for helping me

PS : ( I managed to recover the data,it looks like that and the coordinates )


Solution

  • You are setting coordinates to the geometry (which your screenshot shows is multipolygon) instead of the geometry's coordinates and not updating the type. Try this:

    var geojsonObject = {
     "type": "FeatureCollection",
     "crs": { "type": "name", "properties": { "name": "EPSG:4326" }},
     "features": [
       {
         "type": "Feature",
         "geometry": {
           "type": JSON.parse(myData[2].geom).type,
           "coordinates": JSON.parse(myData[2].geom).coordinates
         }
       }
     ]};