「Vue Leaflet」を導入してみる。
はじめに
しばらく記事を作成できていなかったんですが、今回は久々に作ってみようと思います。ということで作成。
今回の内容は、vue.jsで作成するプロジェクトにleafletを導入するというものです。早速取り掛かってみましょう。
手順
公式サイト内にあるget startedから進めるページに記載があるので、そこでコマンドを実行しましょう。 https://vue2-leaflet.netlify.app/quickstart/
実行コマンドは以下になります。
npm install leaflet vue2-leaflet --save
コマンド実行後、公式サイトの表示に従ってleafeltを利用して地図を表示したいページに以下の記載を追加しましょう。
<template> <l-map style="height: 300px" :zoom="zoom" :center="center"> <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer> <l-marker :lat-lng="markerLatLng"></l-marker> </l-map> </template> <script> import {LMap, LTileLayer, LMarker} from 'vue2-leaflet'; export default { components: { LMap, LTileLayer, LMarker }, data () { return { url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors', zoom: 15, center: [51.505, -0.159], markerLatLng: [51.504, -0.159] }; } } </script>
上記のコードはあくまでもモックアップなので、実際に利用するときは自分で表示したい形になるように色々合わせていきましょう。
細かい説明は置いといて、以下のような形にソースコードを変えてみました。
<template> <v-container> <v-row class="text-center" dense no-gutters> <v-col> <h1>Home</h1> </v-col> </v-row> <v-row justify="center" dense no-gutters> <v-col> <l-map ref="map" id="mainMap" :zoom="zoom" :center="center"> <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer> </l-map> </v-col> </v-row> </v-container> </template> <script> import 'leaflet/dist/leaflet.css' import {LMap, LTileLayer} from 'vue2-leaflet'; export default { name: 'Home', components: { LMap, LTileLayer, }, data () { return { url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors', zoom: 15, center: [51.505, -0.159], markerLatLng: [51.504, -0.159] }; } } </script> <style> @media screen and (max-width:639px) { #mainMap { height: 530px; } } @media screen and (min-width:640px) and (max-width:1369px) { #mainMap { height: 600px; } } @media screen and (min-width:1370px) { #mainMap { height: 800px; } } .leaflet-control-container::after { content: url(https://maps.gsi.go.jp/image/map/crosshairs.png); z-index: 1000; display: block; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style>
leaflet.css等も導入し、更にデザインの面でも対応できるように変えてます。 基本線となる部分については特に修正などは加えていません。
この状態で起動してみると、こんな感じになります。
中心部分への十字マーク表示は、css利用で行っているものになります。
ひとまず、地図を表示するというところまで無事に行うことができました。次回以降は、具体的な機能などについて追加していければなと思います。
おわりに
かなり久々に記事を作成したんですが、やはり仕事とは別でやってて面白いですね。
参考
- 公式
https://vue2-leaflet.netlify.app/
- ボイラープレートの記事(Qiita)