我将mapbox-gl: 1.9.1
与vue: 2.6.11
一起使用。
<head>
...
<script src="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.css" rel="stylesheet" />
<title><%= htmlWebpackPlugin.options.title %></title>
...
<template>
<div id="mapId" class="map" ref="mapElement"></div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator"
import { Map, MapboxOptions, NavigationControl } from "mapbox-gl"
const mapOptions = {
accessToken: process.env.VUE_APP_MAPBOX_ACCESSTOKEN,
style: "mapbox://styles/mapbox/satellite-v9",
center: { lng: -73.647384, lat: 45.201385 },
zoom: 16
}
@Component
export default class MapComponent extends Vue {
public $refs!: {
mapElement: HTMLElement
}
private map: Map = new Map()
constructor() {
super()
}
private mounted() {
this.initMap()
}
private initMap(): void {
const options = { container: this.$refs.mapElement, ...mapOptions }
this.map = new Map(options)
this.map.addControl(new NavigationControl())
}
}
</script>
<style lang='stylus' scoped>
.map {
height: 100%;
width: 100vw;
}
</style>
我已经尝试过container:this.$refs.mapElement
和container: "mapId"
地图显示在网页上,但是我可以在控制台中删除该错误:
vue.runtime.esm.js?2b0e:1888 Error: Invalid type: 'container' must be a String or HTMLElement.
at new r (mapbox-gl.js?e192:33)
我查看了Vue.js docs,也使用了vue.js来研究类似的问题,但是它仍然无法正常工作。有人对此有意见吗?
您的问题是这条线
private map: Map = new Map()
无论何时创建组件,这都会尝试创建没有选项的Map
实例。
只需定义私有属性,直到initMap()
才初始化它,即
private map!: Map
您可以看到here,其中Map
构造函数将检查container
是string
还是HTMLElement
,如果不是,则抛出此错误
if (typeof options.container === 'string') {
this._container = window.document.getElementById(options.container);
if (!this._container) {
throw new Error(`Container '${options.container}' not found.`);
}
} else if (options.container instanceof HTMLElement) {
this._container = options.container;
} else {
throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);
}