スポンサーリンク

Ionic4とleaflet.jsとOpenStreetMapで現在位置を地図で表示するPWAを作成してみる

前回はVue.jsで現在地を地図表示してみました。

今回は、同じことをIonic4でやってみたいと思います。

スポンサーリンク

開発環境

Windows 10 Pro 1803
nvm-windows 1.1.7
node 12.2.0
npm 6.9.0
ionic@5.2.7
git version 2.17.1.windows.2

Node.jsをインストールした状態で、npm install -g ionic@latestでIonic CLIをインストールしています。

nvm --version
nvm list
npm install -g ionic@latest
ionic -V

新規Ionic4アプリの作成

C:/ionic/ フォルダをVisualStudioCodeで開き、Ctrl+@でコマンドプロンプトを開き、以下を入力します。
後で、CapacitorのGeolocationを利用したいので、--capacitorオプションをつけておきます。
5分くらいかかります。
Ionic(Angular)のデメリットは、アプリ新規作成時の時間が5分くらいと非常に長いことにあります。(Vueだと1分くらいの印象です。)

ionic start ionic4-leaflet-map-gps2 tabs --type=angular --capacitor

次に以下を入力して、一旦、Ionic4アプリを起動してみます。

cd ionic4-leaflet-map-gps2
ionic serve

いったん、Ctrl+C ⇒ y + Enter でサーバを停止します。
さらに、VisualStudioCodeを閉じます。

地図表示ライブラリLeaflet.jsのインストールと初期設定

地図表示ライブラリであるLeaflet.jsを、以下の流れでインストールします。

  1. leafletのインストール
  2. @types/leafletの–save-devインストール
  3. angular.jsonの編集
  4. /node_modules/leaflet/dist/ フォルダから、images/ フォルダを、/src/assets/ フォルダにコピー&ペースト

C:/ionic/ionic4-leaflet-map-gps2/ フォルダをVisualStudioCodeで開き、Ctrl+@でコマンドプロンプトを開き、以下を入力します。

npm install leaflet --save
npm install @types/leaflet --save-dev

こちらを参考に、angular.jsonを変更します。
“styles”: [] の最後に、 , { input”: “./node_modules/leaflet/dist/leaflet.css” } を追加します。

"styles": [
  {
    "input": "src/theme/variables.scss"
  },
  {
    "input": "src/global.scss"
  },
  {
    "input": "./node_modules/leaflet/dist/leaflet.css"
  }
],

(変更前)

(変更後)

C:/ionic/ionic4-leaflet-map-gps2/node_modules/leaflet/dist/ フォルダから、images/ フォルダを、
:/ionic/ionic4-leaflet-map-gps2/src/assets/ フォルダにコピー&ペーストします。

Tabテンプレートの設定

Ctrl+@で ionic serveして開発サーバを起動しておきます。

src/app/tabs/tabs.page.html を編集します。

(変更前)

(変更後)

地図の表示(tab1.page.html)

Tab1でLeafletを用いて地図を表示します。

src/app/tab1/tab1.page.html(ソースコード

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      Ionic Leaflet OpenMapStreet
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div id="mapId" style="width: 100%; height: 100%">
  </div>
</ion-content>

(変更前)

(変更後)

src/app/tab1/tab1.page.ts(ソースコード) に以下を追加します。

import { Component } from '@angular/core';
import { Map, latLng, tileLayer, Layer, marker } from 'leaflet';

// 一部省略
export class Tab1Page {
  map: Map;

  ionViewDidEnter() { 
    this.leafletMap();
  }

  leafletMap() {
    // 地図表示
    this.map = new Map('mapId').setView([35.685988,139.753947], 15);
    tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);
    marker([35.685988,139.753947], {
      icon: icon({
          iconSize: [ 25, 41 ],
          iconAnchor: [ 13, 41 ],
          iconUrl: 'assets/images/marker-icon.png',
          shadowUrl: 'assets/images/marker-shadow.png'
      })
    }).addTo(this.map);
  }

  /** Remove map when we have multiple map object */
  ionViewWillLeave() {
    this.map.remove();
  }
}

(変更前)

(変更後)

今回は用いませんでしたが、

@asymmetrik/ngx-leaflet

を用いる方法の方が、Leaflet公式ドキュメント(英語)のExample通りにコードを書くことができるので、便利かもしれません。
今回は @asymmetrik/ngx-leaflet を用いていないので、”L.map.xxx”と記載せずに、上の方で”import { map } from “leaflet” “と記載して、下の方で”map.xxx”と記載するような感じになります。

ここまでのコード
https://github.com/adash333/ionic4-leaflet-map-gps2/tree/8cb1602b081cb328d1b0f2be9c3cad8631f9a519

現在の緯度経度を表示(tab2.page.html)

CapacitorのGeolocationを用いて現在の緯度経度を表示します。
(参考:Ionic4とCapacitorでgps取得

src/app/tab2/tab2.page.html を以下のように編集します。

<ion-header>
  <ion-toolbar color="secondary"> 
    <ion-title>
      Capacitor Geolocation
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-card>
    <ion-card-header>
      <ion-card-title>現在地の座標</ion-card-title>
    </ion-card-header>
    <ion-card-content>
      <ion-item>緯度: {{ latitude }}</ion-item>
      <ion-item>経度: {{ longitude }}</ion-item>
    </ion-card-content>
  </ion-card>
</ion-content>

(変更前)

(変更後)

次に、 src/app/tab2/tab2.page.ts を以下のように編集します。

import { Geolocation} from '@capacitor/core';
 
//一部省略
 
export class Tab2Page {
  latitude: number;
  longitude: number;
 
  constructor() {
    this.getLocation();
  }
 
  async getLocation() {
    const position = await Geolocation.getCurrentPosition();
    this.latitude = position.coords.latitude;
    this.longitude = position.coords.longitude;
  }
}

(変更前)

(変更後)

5秒おきに現在位置を更新してマーカーと地図を移動する→うまくいかず。。。

以下のように src/app/tab1/tab1.page.ts を書き換えて、5秒おきに現在値を更新するようにしてみます。

    // マップオブジェクト生成
    // データソースはOpenStreetMap
    const map = L.map("app").addLayer(
      L.tileLayer("https://{s}.tile.osm.org/{z}/{x}/{y}.png", {
    		attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, '
    	})
    );
    // 位置情報検索
    setInterval(() => {
      map.locate({ setView: true, maxZoom: 20, zoom: 20 });
    }, 5000);
    // map.locate({ setView: true, maxZoom: 10 });
    // 位置情報取得成功処理
    function onLocationFound(e) {
      var radius = e.accuracy / 2;
      L.marker(e.latlng).addTo(map);
      //.bindPopup("You are within " + radius + " meters from this point")
      //.openPopup();
      L.circle(e.latlng, radius).addTo(map);
    }
    map.on("locationfound", onLocationFound);
    // 位置情報取得エラー処理
    function onLocationError(e) {
      alert(e.message);
    }
    map.on("locationerror", onLocationError);
  }

いろいろやったのですが、マーカーを表示することができませんでした。。。

参考サイト


https://leafletjs.com/reference-1.5.0.html
Leaflet.js 公式ドキュメント

http://edupala.com/how-to-add-leaflet-map-in-ionic-4/
How to add Leaflet Map in Ionic -4 or Angular

https://stackoverflow.com/questions/53945625/leaflet-map-and-ionic-4

IonicとLeafletで地図表示

https://qiita.com/uedayou/items/30f88d88238f648e8ee6
@uedayou
2018年07月09日に更新
Angular6とLeafletで地図を表示する

https://qiita.com/spice/items/22811539d3561bd1e73c
@spice
2018年05月04日に更新
Angularでleafletを使っちゃうぞ



作成中

Ionic4

Posted by twosquirrel