vue创建最简单的leaflet项目

在创建leaflet项目前,先安装环境,请阅读:

本人示例环境:

1、确保nodejs已经安装好,建议使用nvm,这样可以切换多个版本的nodejs,其他环境按照以上文档准备好;

2、打开cmd窗口,使用 **vue create leafletapp** 来创建基础项目,我选择vue3默认配置:

3、使用开发软件打开leafletapp项目,我使用VSCode:

4、在终端使用 npm install leaflet --save 来安装leaflet 组件

5、新建LeafletMap组件来加载地图

LeafletMap.vue:

<template>
  <div id="map-container"></div>
</template>
<script>
import L from "leaflet";
export default {
  name: "myMap",
  components: {},
  created() {},
  mounted() {
    // 必须在组件挂载之后初始化地图,不然会报错 
    this.initMap();
  },
  methods: {
    initMap() {
      const map = L.map("map-container", {
        crs: L.CRS.EPSG3857,
        center: [24.886566,102.830513],
        zoom: 11
      });
      console.log("map:", map);
      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>contributors'
      }).addTo(map);
    }
  }
};
</script>

<style scoped>
#map-container {
  position: absolute;
  top: 60px;
  left: 0;
  /* height: 100%; */
  width: 100%;
  bottom: 0;
}
</style>

6、修改App.vue

(1)删除template中的HelloWorld组件,添加上一步创建的LeafletMap组件

(2)import中删除原来的HelloWorld组件,导入LeafletMap 

(3)components组件中将HelloWorld更改为LeafletMap 

<template>
  <!-- <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/> -->
  <LeafletMap />
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'
import LeafletMap from './components/LeafletMap.vue'

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

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 7、保存修改后运行npm run serve,即可看到leaflet地图:

 

参考链接:https://blog.csdn.net/cuclife/article/details/126745283 

<本文完>

 

posted @ 2023-08-16 09:35  孤草之魂  阅读(474)  评论(0编辑  收藏  举报