【问题标题】:Using Mapbox GL JS in Vue after initialization初始化后在 Vue 中使用 Mapbox GL JS
【发布时间】:2020-10-06 16:03:27
【问题描述】:

下面是我的Map.vue,部分代码已缩写,因此我不公开任何信息。地图是我的应用程序的一个组件,我想向它添加一些交互。但是,我的method 不起作用,说read property 'getPitch' of undefined。如何初始化地图,以便以后 Mapbox 的功能仍然可用?

<template>
    <div id="map" class="map">
        <button @click="getPitch">Test</button>
    </div>

</template>

<script>
import mapboxgl from 'mapbox-gl';

export default {
    name: "Map",
    data() {
        return {
        };
    },
    props: {
        mapdata: {
            type: Object,
            default: () => { return {}; }
        }
    },
    beforeUpdate() {
            
        mapboxgl.accessToken = "...";

        const map = new mapboxgl.Map({
            container: "map",
            style: "...",
            center: ...,
            zoom: 11.85,
        });

        let mapRecords = this.mapdata.data;

        map.once('styledata', function() {

            map.addSource('...', {
            ...
            });

            map.addLayer({
            ...
            })
        });

    },
    methods: {
        getPitch() {
            map.getPitch();
        }
    }
};
</script>

<style scoped>
...
</style>

已解决

首先,将beforeUpdate() 中的所有map 实例更改为this.map。然后,在getPitch 函数中,添加这一行:let map = this.map;

【问题讨论】:

  • 我假设这又是 Vue 3?

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


【解决方案1】:

beforeUpdate 看起来不像正确的钩子。您可能应该使用mounted

此外,您的变量 map 超出了您的 getPitch 方法的范围。

【讨论】:

  • beforeUpdate 仍然有效,因为我正在等待来自父级的数据(mapdata 对象)。至于第二部分,你是对的。
  • 但是,如果 mapdata 发生变化,您将创建一个全新的 map 实例,这可能不是您想要的。
猜你喜欢
  • 1970-01-01
  • 2019-11-19
  • 2017-01-26
  • 2016-06-05
  • 2021-01-30
  • 2016-07-07
  • 2017-03-14
  • 2017-02-15
  • 2020-07-30
相关资源
最近更新 更多