Search code examples
openlayersopenlayers-6

geoJson object not drawing with open layers


I have a codepen demonstrating the issue at: https://codepen.io/ericg_off/pen/OJvqZMx

I can get this geojson object to draw with leaflet - https://codepen.io/ericg_off/pen/OJvqEdL

I am using v6.15.1.

I believe the solution will involve the projection features of OpenLayers.

What do I need to change so the geojson object will draw?

HTML:

<div id="map"></div>

CSS:

#map {
  height: 512px;
  width: 1024px;
}

JS:

const kuwait = {
  type: "FeatureCollection",
  features: [
    {
      type: "Feature",
      geometry: {
        type: "Polygon",
        coordinates: [
          [
            // lat/lon order
            // [47.974519077349896, 29.9758192001485],
            // [48.18318851094448, 29.534476630159766],
            // [48.09394331237642, 29.306299343375002],
            // [48.416094191283946, 28.55200429942667],
            // [47.708850538937384, 28.526062730416143],
            // [47.45982181172283, 29.002519436147224],
            // [46.568713413281756, 29.09902517345229],
            // [47.30262210469096, 30.05906993257072],
            // [47.974519077349896, 29.9758192001485]
            
            // lon/lat order
            [47.974519077349896, 29.9758192001485],
            [48.18318851094448, 29.534476630159766],
            [48.09394331237642, 29.306299343375002],
            [48.416094191283946, 28.55200429942667],
            [47.708850538937384, 28.526062730416143],
            [47.45982181172283, 29.002519436147224],
            [46.568713413281756, 29.09902517345229],
            [47.30262210469096, 30.05906993257072],
            [47.974519077349896, 29.9758192001485]            
          ]
        ]
      }
    }
  ]
};

const styles = {
  Polygon: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "blue",
      lineDash: [4],
      width: 3
    }),
    fill: new ol.style.Fill({
      color: "rgba(0, 0, 255, 0.1)"
    })
  })
};

const styleFunction = function (feature) {
  const featureType = feature.getGeometry().getType();
  return styles[featureType];
};

const vectorSource = new ol.source.Vector({
  features: new ol.format.GeoJSON().readFeatures(kuwait)
});

const vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: styleFunction
});

const map = new ol.Map({
  target: "map",
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    vectorLayer
  ],
  view: new ol.View({
    center: [0, 0],
    zoom: 2
  })
});

Solution

  • When parsing the GeoJSON you need to specify the projection the features are to be viewed in

    features: new ol.format.GeoJSON({featureProjection: 'EPSG:3857'}).readFeatures(kuwait)
    

    https://codepen.io/mike-000/pen/oNqVMEK