首页 > 解决方案 > 为什么 openlayers 地图在 vue-cli 3 中不起作用

问题描述

我已经通过添加 ol 包到我的 vue-cli 项目中

npm 安装

但地图不加载。没有错误,我只是在结果源中找到了一个空的 div。

这是我的代码=>

html部分:

<div id="map-container"></div>

js部分:

import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZSource from 'ol/source/XYZ';

export default {
    name: "page",
    data() {
        return {
            ...
        }
    },
    methods: {

        initMap: function () {
            new Map({
                target: 'map-container',
                view: new View({
                center: [0, 0],
                zoom: 2
            })
        });
    },
    mounted: function () {
            this.initMap();
    },
}

注意=> 在某些地方我发现我必须将 init 函数调用为:

this.$nextTick(function () {
            initMap();
        })

但这没有任何区别。

伙计们,我的时间不多了,所以请帮助我。感谢所有想要帮助的人

标签: javascriptvue.jsnpmvue-cli-3openlayers-5

解决方案


看起来您缺少 TileLayer。像这样的东西:

new Map({
  target: "map-container",
  layers: [
    new TileLayer({
      source: new XYZ({
        url: "https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      })
    })
  ],
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

推荐阅读