我试图用vue-cli-3实现Openlayers,但似乎我做得不对,我遗漏了一些东西。
首先,我安装了vue cli
npm install @vue/cli -g然后,我添加了额外的依赖项,或者更准确地说,添加了OpenLayers库。
npm install ol.但是,我在全局注册ol (在main.js文件中)中添加/注册依赖项方面失败了。
在我的App.vue文件中,当我导入这样的文件时,它不工作。我收到了这两个错误
Vue警告:nextTick中的错误:"ReferenceError: ol未定义“ 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>我的问题是这个。是否可以像在L页上推荐的那样使用模块导入元素,是否可以在main.js文件中全局注册ol包?
发布于 2018-09-12 19:23:25
好吧,经过进一步的咨询,我终于想出了办法。这里是一个有用的例子,希望它能帮助到别人。
// 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
})
}发布于 2018-09-11 21:46:23
您永远不会导入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项目中尝试了它,该函数运行时没有任何引用错误
https://stackoverflow.com/questions/52284275
复制相似问题