【问题标题】:Vue.js mapbox-gl Error: Invalid type: 'container' must be a String or HTMLElementVue.js mapbox-gl 错误:无效类型:“容器”必须是字符串或 HTMLElement
【发布时间】:2020-06-11 01:50:16
【问题描述】:

我正在使用 mapbox-gl: 1.9.1vue: 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.mapElementcontainer: "mapId"网页上的地图显示,但是可以在Console中消除错误:

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 查看了类似的问题,但它仍然无法正常工作。有人对此有意见吗?

【问题讨论】:

    标签: vue.js vuejs2 mapbox-gl-js


    【解决方案1】:

    你的问题是这一行

    private map: Map = new Map()
    

    这将尝试创建一个 Map 实例,并且在创建组件时没有任何选项。

    只定义私有属性而不初始化它直到initMap(),即

    private map!: Map
    

    您可以看到here,其中Map 构造函数检查containerstring 还是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.`);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 2019-12-24
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多