从es6创建对象并在js文件中使用openlayers映射

时间:2019-04-17 13:09:15

标签: javascript ecmascript-6 openlayers

我想创建自己的API,我用es6并使用javascript核心创建了类和对象。

当我使用npm运行此代码时,出现此错误; 未捕获的ReferenceError:未定义映射器

您认为我在哪里遇到错误?

index.js; OpenLayers的代码功能

import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

window.onload = config;
let mapper;

function config() {
    mapper = new IMapper();
}

export class IMapper{
    constructor(){
    }

   initMap () {
        const map = new Map({
            target: 'map',
            layers: [
                new TileLayer({
                    source: new OSM()
                })
            ],
            view: new View({
                center: [0, 0],
                zoom: 0
            })
        });
    }
}

index.html;在js核心中调用了es6代码,但出现此错误

<html>
<head>
    <meta charset="utf-8">
    <title>Using Parcel with OpenLayers</title>
    <style>
        #map {
            width: 400px;
            height: 250px;
        }
    </style>
    <script type="module" src="index.js"></script>
</head>
<body>
<div id="map"></div>
<script>
    mapper.initMap();
</script>
</body>
</html>

package.json

 {
  "name": "ol-parcel",
  "version": "1.0.0",
  "description": "Example using OpenLayers with Parcel",
  "scripts": {
  "start": "parcel index.html",
  "build": "parcel build --public-url . *.html *.js"
  },
    "dependencies": {
    "ol": "^5.1.2"
  },
  "devDependencies": {
        "parcel-bundler": "^1.9.4"
  }    
}

感谢您的回复...

1 个答案:

答案 0 :(得分:0)

您需要实际调用config函数。

window.onload = config();