Ad

Cannot Read Property 'Tile' Of Undefined In ReactJS

- 1 answer

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;
Ad

Answer

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>
    )
  }
}
Ad
source: stackoverflow.com
Ad