dayjournal memo

Total 974 articles!!

Try #045 – ReactでプレーンなLeafletとMapbox GL JSとOpenLayersの開発環境を構築してみた

Yasunori Kirimoto's avatar

画像

画像

画像

画像




画像




ReactでプレーンなLeafletとMapbox GL JSとOpenLayersの開発環境を構築してみました!



ReactでLeafletとMapbox GL JSとOpenLayersを利用する時に、ラッパーライブラリを利用しているかたもいると思いますが、今回はプレーンな開発環境を構築してみました!



事前準備



共通設定

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react",
        // 暗黙のany型をエラーにしない
        "noImplicitAny": false
    },
    "include": ["src"]
}

ライブラリがうまく動作しないので、今回は暗黙のany型をエラーにしない設定をします。

// 暗黙のany型をエラーにしない
"noImplicitAny": false


/src

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import MapPane from './MapPane';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
    <React.StrictMode>
        <App />
        <MapPane />
    </React.StrictMode>,
    document.getElementById('root')
);

serviceWorker.unregister();

新規作成する「MapPane.tsx」を、「index.tsx」で読み込みます。

import MapPane from './MapPane';

<MapPane />


React x Leaflet


ライブラリをインストールします。

npm install leaflet
npm install @types/leaflet


次に、地図を表示させるためのコードを書きます。今回は、「MapPane.tsx」と「MapPane.css」を作成します。


全体構成

画像



/src


MapPane.tsx

import React, { Component } from 'react';
// Leaflet読み込み
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import './MapPane.css';

class MapPane extends Component {
    map: any;
    container: any;
    m_streets: any;

    componentDidMount() {
        // 背景地図設定
        this.m_streets = L.tileLayer(
            'https://api.maptiler.com/maps/jp-mierune-streets/256/{z}/{x}/{y}.png?key=[APIキー]',
            {
                attribution:
                    '<a href="https://maptiler.jp/" target="_blank">© MIERUNE</a> <a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>',
            }
        );

        // マップ設定
        this.map = L.map(this.container, {
            center: [35.681, 139.767],
            zoom: 14,
            zoomControl: true,
            layers: [this.m_streets],
        });
    }

    render() {
        return <div className={'map'} ref={(e) => (this.container = e)} />;
    }
}

export default MapPane;

Leaflet関係のライブラリを読み込みます。

// Leaflet読み込み
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

背景地図を設定します。

// 背景地図設定
this.m_streets = L.tileLayer(
    'https://api.maptiler.com/maps/jp-mierune-streets/256/{z}/{x}/{y}.png?key=[APIキー]',
    {
        attribution:
            '<a href="https://maptiler.jp/" target="_blank">© MIERUNE</a> <a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>',
    }
);

マップを設定します。

// マップ設定
this.map = L.map(this.container, {
    center: [35.681, 139.767],
    zoom: 14,
    zoomControl: true,
    layers: [this.m_streets],
});


/src


MapPane.css

.map {
    z-index: 0;
    height: 1000px;
    text-align: left;
}


ローカルサーバーで確認

npm start


ローカルサーバーを立ち上げると、マップが表示されます。

画像



React x Mapbox GL JS


ライブラリをインストールします。

npm install mapbox-gl
npm install @types/mapbox-gl


次に、地図を表示させるためのコードを書きます。今回は、「MapPane.tsx」を作成します。


全体構成

画像



/src


MapPane.tsx

import React, { Component } from 'react';
// Mapbox GL JS読み込み
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import './MapPane.css';

class MapPane extends Component {
    map: any;
    container: any;

    componentDidMount() {
        this.map = new mapboxgl.Map({
            container: this.container,
            style:
                'https://api.maptiler.com/maps/jp-mierune-streets/style.json?key=[APIキー]',
            center: [139.767, 35.681],
            zoom: 13,
        });

        // コントロール関係表示
        this.map.addControl(
            new mapboxgl.NavigationControl({
                visualizePitch: true,
            })
        );
    }

    render() {
        return <div className={'map'} ref={(e) => (this.container = e)} />;
    }
}

export default MapPane;

Mapbox GL JS関係のライブラリを読み込みます。

// Mapbox GL JS読み込み
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

マップを設定します。

// マップ設定
this.map = new mapboxgl.Map({
    container: this.container,
    style:
        'https://api.maptiler.com/maps/jp-mierune-streets/style.json?key=[APIキー]',
    center: [139.767, 35.681],
    zoom: 13,
});

コントロール関係を表示します。

// コントロール関係表示
this.map.addControl(
    new mapboxgl.NavigationControl({
        visualizePitch: true,
    })
);


/src


MapPane.css

.map {
    z-index: 0;
    height: 1000px;
    text-align: left;
}


ローカルサーバーで確認

npm start


ローカルサーバーを立ち上げると、マップが表示されます。

画像



React x OpenLayers


ライブラリをインストールします。

npm install ol
npm install @types/ol


次に、地図を表示させるためのコードを書きます。今回は、「MapPane.tsx」と「MapPane.css」を作成します。


全体構成

画像



/src


MapPane.tsx

import React, { Component } from 'react';
// OpenLayers読み込み
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { fromLonLat } from 'ol/proj';
import 'ol/ol.css';
import './MapPane.css';

class MapPane extends Component {
    map: any;
    container: any;

    componentDidMount() {
        // マップ設定
        this.map = new Map({
            target: this.container,
            layers: [
                new TileLayer({
                    source: new XYZ({
                        url:
                            'https://api.maptiler.com/maps/jp-mierune-streets/256/{z}/{x}/{y}.png?key=[APIキー]',
                        attributions:
                            '<a href="https://maptiler.jp/" target="_blank">© MIERUNE</a> <a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>',
                        attributionsCollapsible: false,
                        tileSize: [256, 256],
                        minZoom: 0,
                        maxZoom: 18,
                    }),
                }),
            ],
            view: new View({
                center: fromLonLat([139.767, 35.681]),
                zoom: 14,
            }),
        });
    }

    render() {
        return <div className={'map'} ref={(e) => (this.container = e)} />;
    }
}

export default MapPane;

OpenLayers関係のライブラリを読み込みます。

// OpenLayers読み込み
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { fromLonLat } from 'ol/proj';
import 'ol/ol.css';

マップを設定します。

// マップ設定
this.map = new Map({
    target: this.container,
    layers: [
        new TileLayer({
            source: new XYZ({
                url:
                    'https://api.maptiler.com/maps/jp-mierune-streets/256/{z}/{x}/{y}.png?key=[APIキー]',
                attributions:
                    '<a href="https://maptiler.jp/" target="_blank">© MIERUNE</a> <a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>',
                attributionsCollapsible: false,
                tileSize: [256, 256],
                minZoom: 0,
                maxZoom: 18,
            }),
        }),
    ],
    view: new View({
        center: fromLonLat([139.767, 35.681]),
        zoom: 14,
    }),
});


/src


MapPane.css

.map {
    z-index: 0;
    height: 1000px;
    text-align: left;
}


ローカルサーバーで確認

npm start


ローカルサーバーを立ち上げると、マップが表示されます。

画像



ReactでプレーンなLeafletとMapbox GL JSとOpenLayersの開発環境の構築ができました!


用途により直接読み込むかラッパーライブラリを利用するかの選択は必要となりそうですが、どちらにしてもReactでマップライブラリを利用することが可能です。実案件では、プレーンな機能やプラグインを利用できる今回の直接読み込むパターンを利用するのが自由度が高そうですが、マーカーを表示するなどのシンプルな用途であればラッパーライブラリを利用したほうが手軽で操作しやすいかもしれません。


以前、「Try #044 – ReactでLeafletとMapbox GL JSとOpenLayersの開発環境を構築してみた」で紹介したラッパーライブラリの方法と比べてみて頂ければと思います!



React・Leaflet・Mapbox GL JS・OpenLayersについて、他にも記事を書いています。よろしければぜひ。
tags - React
tags - Leaflet
tags - Mapbox GL JS
tags - OpenLayers



book

Q&A