0

I am adding a map using Open Layer in React JS and I have imported all the required libraries. but I am getting an error as "Cannot read property 'Tile' of undefined".

What is wrong in the below code?

Code:

import React, { Component } from 'react';
import 'ol/ol.css';
import ol from 'ol';
import Map from 'ol/map';
import View from 'ol/view';
import Tile from 'ol/layer/tile';

class MapComponent extends Component {

    componentDidMount() {
        var map = new ol.Map({
            target: 'map',
            layers: [
              new ol.layer.Tile({
                source: new ol.source.OSM()
              })
            ],
            view: new ol.View({
              center: ol.proj.fromLonLat([37.41, 8.82]),
              zoom: 4
            })
          })
    }
    render() {

        return (
            <div id="map"></div>
        )
    }
}
export default MapComponent;
halfer
  • 19,824
  • 17
  • 99
  • 186
Subburaj
  • 2,294
  • 3
  • 20
  • 37

1 Answers1

2

I would recommend to use some reactified libs, like react-ol for instance. Although for this particular question try just Tile instead of ol.layer.Tile and apply same principle for consequetive errors of same type. The following code worked for me: here is the codebox

import React, { Component } from "react";
import ReactDOM from "react-dom";
import 'ol/ol.css';
import ol from 'ol';
import Map from 'ol/map';
import View from 'ol/view';
import Tile from 'ol/layer/tile';
import OSM from 'ol/source/osm';
import proj from 'ol/proj';

class MapComponent extends Component {

  componentDidMount() {
    var map = new Map({
      target: 'map',
      layers: [
        new Tile({
          source: new OSM()
        })
      ],
      view: new View({
        center: proj.fromLonLat([37.41, 8.82]),
        zoom: 4
      })
    })
  }
  render() {

    return (
      <div id="map"></div>
    )
  }
}
seethrough
  • 712
  • 4
  • 15
  • I am getting an error as "./src/components/MapComponent.js Module not found: Can't resolve 'Tile' in 'C:\Projects\ras_app\react_spa\src\components'" . – Subburaj Jun 14 '18 at 16:16
  • updated my answer. so I ended importing modules explicitly, although explicit import through should also work. At least try this. – seethrough Jun 14 '18 at 18:04