[Vue.js]leaflet使ってみる

> npm install leaflet @types/leaflet @vue-leaflet/vue-leaflet

main.tsに追記

import { createApp } from "vue";
import { createPinia } from "pinia";

import App from "./App.vue";
import router from "./router";

// Leaflet
import "leaflet/dist/leaflet.css"

const app = createApp(App);

app.use(createPinia());
app.use(router);

app.mount("#app");

MapPane.vueを新規作成

<template>
  <div class="mapPane">
    <!--マップ-->
    <l-map :zoom="zoom" :center="center">
      <!--レイヤーコントロール-->
      <l-control-layers position="topright"></l-control-layers>
      <!--レイヤ設定-->
      <l-tile-layer
        v-for="tileProvider in tileProviders"
        :key="tileProvider.name"
        :name="tileProvider.name"
        :visible="tileProvider.visible"
        :url="tileProvider.url"
        :attribution="tileProvider.attribution"
        layer-type="base"
      ></l-tile-layer>
      <!--マーカー-->
      <l-marker :lat-lng="marker"></l-marker>
    </l-map>
  </div>
</template>

<script lang="ts">
import {
  LMap,
  LTileLayer,
  LControlLayers,
  LMarker,
} from "@vue-leaflet/vue-leaflet";

export default {
  name: "MapPane",
  components: {
    LMap,
    LTileLayer,
    LControlLayers,
    LMarker,
  },
  data() {
    return {
      center: [35.681, 139.763],
      zoom: 14,
      marker: [35.681, 139.763],
      tileProviders: [
        {
          name: "OpenStreetMap",
          visible: true,
          url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
          attribution:
            '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        },
        {
          name: "OpenStreetMap CyclOSM",
          visible: false,
          url: "https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
          attribution:
            '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        },
      ],
    };
  },
};
</script>

<style scoped>
.mapPane {
  height: 800px;
  margin: 0;
  text-align: left;
}
</style>

AboutViewe.vueに追記

<script setup lang="ts">
// マップコンポーネント読み込み
import MapPane from "@/components/MapPane.vue";
</script>

<template>
  <MapPane></MapPane>
</template>

<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>

“@vue-leaflet/vue-leaflet”のインポート部分でエラーが出るので定義追加

declare module '@vue-leaflet/vue-leaflet' {
    import type { DefineComponent } from 'vue';
    export const LMap: DefineComponent;
    export const LIcon: DefineComponent;
    export const LTileLayer: DefineComponent;
    export const LMarker: DefineComponent;
    export const LControlLayers: DefineComponent;
    export const LTooltip: DefineComponent;
    export const LPopup: DefineComponent;
    export const LPolyline: DefineComponent;
    export const LPolygon: DefineComponent;
    export const LRectangle: DefineComponent;
  }

実行

> npm run dev

コメントを残す