无法在ReactJS中读取未定义的属性“Tile”

时间:2018-06-14 14:02:56

标签: reactjs openlayers openlayers-3

我在React JS中使用Open Layer添加了一个地图,我已经导入了所有必需的库。但我收到一个错误,因为“无法读取未定义的属性'Tile'。”

以下代码有什么问题?

代码:

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;

1 个答案:

答案 0 :(得分:1)

我建议使用一些已恢复的库,例如react-ol。虽然针对此特定问题,请尝试Tile而不是ol.layer.Tile  并对相同类型的后果性错误应用相同的原则。以下代码适用于我: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>
    )
  }
}