【问题标题】:Is it possible to add OpenLayers library to vue-cli 3是否可以将 OpenLayers 库添加到 vue-cli 3
【发布时间】:2018-09-11 21:11:03
【问题描述】:

我正在尝试使用 vue-cli-3 实现 Openlayers,但似乎我做错了,我错过了一些东西。

首先,我安装了 vue cli

npm install @vue/cli -g

然后我添加了额外的依赖,或者更准确地说是 OpenLayers 库。

npm install ol.

但我在全局注册 ol 时添加/注册依赖项(在 main.js 文件中)以某种方式失败

当我导入这样的文件时,在我的 App.vue 文件中它不起作用。我收到这两个错误

[Vue 警告]:nextTick 中的错误:“ReferenceError: ol is not defined”

ReferenceError: ol 未定义

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

export default {

  data() {
    return {
      testing: 'SomeTests',
    }
  },
  mounted() {
    this.$nextTick(function () {
      initMap();
    })
  }
}
function initMap() {
  var myMap = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    target: 'map',
    view: new ol.View({
      center: [0, 0],
      zoom: 2,
    })
  })
};

但是当我在 index.html 中包含脚本和链接标记时,上面的代码可以正常工作。

<head>
  <link rel="stylesheet" href="https://openlayers.org/en/v5.2.0/css/ol.css" type="text/css">
  <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.2.0/build/ol.js"></script>
  <title>ol-basic</title>
</head>

我的问题是这样的。是否可以像 ol page 上推荐的那样使用模块导入元素,是否可以在我的 main.js 文件中以某种方式全局注册 ol 包

【问题讨论】:

    标签: javascript vue.js openlayers vue-cli


    【解决方案1】:

    好的,经过额外的咨询,我终于弄明白了。 这是工作示例,希望对某人有所帮助。

    // Import everything from ol
    import 'ol/ol.css';
    import Map from 'ol/Map';
    import View from 'ol/View';
    import TileLayer from 'ol/layer/Tile';
    import XYZ from 'ol/source/XYZ';
    
    function initMap() {
      new Map({
        target: 'map',
        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
        })
      }
    

    【讨论】:

      【解决方案2】:

      你永远不会导入ol,因为它是未定义的,因此会给你这些错误。请尝试以下操作:

      // Import everything from ol
      import * as ol from 'ol';
      
      // The OSM and TileLayer API is taken from the OpenLayers API.
      function initMap() {
        var myMap = new ol.Map({
          layers: [
            new TileLayer({
              source: new OSM()
            })
          ],
          target: 'map',
          view: new ol.View({
            center: [0, 0],
            zoom: 2,
          })
        })
      }
      

      我在一个快速的Vue项目中试了一下,函数运行没有任何引用错误

      【讨论】:

      • 嗯,我会在家里试试这个。但如果我理解正确,您只能按照官方网站openlayers.org/en/latest/doc/tutorials/bundle.html 上的建议导入您需要的模块
      • 当然,感谢您的努力和时间 :)
      • 如果你想这样做,你也可以导入你需要的模块! import { Map, TileLayer, OSM, View } from 'ol'
      猜你喜欢
      • 2019-04-20
      • 2021-10-26
      • 2017-12-21
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 2018-10-11
      • 2018-12-21
      • 1970-01-01
      相关资源
      最近更新 更多