10
11

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

Last updated at Posted at 2020-11-03

try-045_05.gif


react.png

leaflet.png

mapboxgljs.png

openlayers.png


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

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


1. 事前準備


2. 共通設定

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 />

3. 各ライブラリ設定

React x Leaflet


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


npm install leaflet
npm install @types/leaflet

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

try-045_01.png

/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

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

sample01.gif


React x Mapbox GL JS


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

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

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

try-045_02.png


/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

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

try-045_05.gif


React x OpenLayers


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

npm install ol
npm install @types/ol

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

try-045_03.png


/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

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

sample03.gif


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

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

お好きなマップライブラリでゼヒ試してみてください!


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


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



book

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11