Search code examples
reactjsopenlayersgeojson

Openlayers GeoJSON is at the wrong place


I'm new to Openlayers and have little experience with leaflet. A GeoJSON which worked in leaflet is at the completly wrong place (little red dot)

I can understand that it has something to do with projection, but as i'm new i could not find a working projection. As the GeoJSON worked perfectly in leaflet, i'm assuming its EPSG:3857 the file can be found here

enter image description here

and if you zoom very far in, it is projected enter image description here

import React, { useEffect, useState } from 'react'
import isDefined from '../../lib/utils/is-defined'
import OlMap from 'ol/Map'
import OlView from 'ol/View'
import OlLayerTile from 'ol/layer/Tile'
import OlSourceOSM from 'ol/source/Osm'
import GeoJSON from 'ol/format/GeoJSON'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style'
import germanyFullGeoJSON from '../../assets/germany_full.json'
import 'ol/ol.css'

const styles = {
  MultiPolygon: new Style({
    stroke: new Stroke({
      color: 'red',
      width: 4
    }),
    fill: new Fill({
      color: 'red'
    })
  })
}

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

const Map = () => {
  const [map, setMap] = useState(null)
  const [zoom, setZoom] = useState(5)
  const [center, setCenter] = useState([546000, 6868000])

  useEffect(() => {
    const format = new GeoJSON()
    const features = format.readFeatures(germanyFullGeoJSON)

    const vectorLayer = new VectorLayer({
      source: new VectorSource({
        features
      }),
      style: styleFunction
    })
    const tempMap = new OlMap({
      target: 'map',
      layers: [
        new OlLayerTile({
          source: new OlSourceOSM()
        }),
        vectorLayer
      ],
      view: new OlView({
        center,
        zoom
      })

    })
    setMap(tempMap)
  }, [])

  if (isDefined(map)) {
    map.getView().setCenter(center)
    map.getView().setZoom(zoom)
    map.render()
  }
  return (
    <div id="map" style={{ width: '100%', height: '100%' }} />
  )
}

export default Map

Solution

  • The default projection of OpenLayers is EPSG:3857. Therefore you need to transform your GeoJSON feature of Germany, which is given in EPSG:4326. Try to fix format as follow setting featureProjection accordingly:

    const format = new GeoJSON({ featureProjection: 'EPSG:3857' });