Mapbox GL JS 可视化项目搭建(vue3.0)

3,283 阅读1分钟

1、vue cli 安装

$ npm install @vue/cli -g

2、查看版本

$ vue -V
@vue/cli 4.5.9

3、新建一个项目

$ vue create mapbox-example
Vue CLI v4.5.9
? Please pick a preset:
  Default ([Vue 2] babel, eslint)
> Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

4、安装 vue-router

yarn add vue-router@4.0.0-alpha.6

5、安装 mapbox-gl

yarn add mapbox-gl

6、新建组件 Map.vue

<template>
  <div id="first-map"></div>
</template>

<script>
import 'mapbox-gl/dist/mapbox-gl.css';
import mapbox from 'mapbox-gl';

export default {
  name: 'Map',
  mounted() {
    mapbox.accessToken = 'YOUR_KEY';
    const mapApp = new mapbox.Map({
      container: 'first-map',
      style: 'mapbox://styles/mapbox/streets-v9',
      center: [120.57229, 31.28505],
      zoom: 9,
    });
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#first-map {
  padding: 0%;
  margin: 0%;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>

7、配置路由

// src\router\index.js
import Map from '../components/Map.vue';
import { createRouter, createWebHistory } from 'vue-router';//和vue2 路由不同
const routerHistory = createWebHistory();

const router = createRouter({
  history: routerHistory,//history写法不同
  routes: [
    {
      path: '/',
      component: Map,
    },
  ],
});

export default router;

8、挂载路由

// src\main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)

app.mount('#app')

9、修改 App.vue

<template>
  <router-view class="container" />
</template>

<script>
export default {
  name: 'App',
  components: {
  },
};
</script>

<style>
html,
body,
#app,
.container {
  padding: 0%;
  margin: 0%;
  width: 100%;
  height: 100%;
}
</style>

10、运行项目

# cd mapbox-example
$ yarn serve

参考资料

https://v3.vuejs.org/guide/introduction.html
https://docs.mapbox.com/mapbox-gl-js/api/