【react】react-leafletで現在地を表示する方法

react-leafletで特定の座標から現在位置に移動するにはleaflet.locatecontrolを 使う必要があります。 インストール方法は以下の通り。 npm install leaflet.locatecontrol –save 簡単なコンポーネントから作っていきます。 子コンポーネント
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>import React, { Component } from "react";<br />import { withLeaflet } from "react-leaflet";<br />import Locate from "leaflet.locatecontrol";</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>class Locate extends Component {<br />componentDidMount() {<br />const { options } = this.props;<br />const { map } = this.props.leaflet;</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">const lc = new Locate(options);
lc.addTo(map);

  lc.start();</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>render() {<br />return null;<br />}<br />}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>export default withLeaflet(Locate);</p>
<pre>
  親コンポーネント
</pre>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>render() {<br />const baseLocateOptions = {<br />position: 'topright',<br />strings: {<br />title: 'タイトルを表示します!'<br />},<br />onActivate: () => {}<br />}</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">return (
  <Map center={this.props.center} zoom={this.props.zoom}>
    <TileLayer
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    />
     <LocateControl options={baseLocateOptions} startDirectly/>
  </Map>
);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>}</p>
<pre>
  とりあえず現在地を出すだけのシンプルなボタンの場合はこれでOK。
>株式会社シーポイントラボ

株式会社シーポイントラボ

TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:〒432-8003
   静岡県浜松市中央区和地山3-1-7
   浜松イノベーションキューブ 315
※ご来社の際はインターホンで「316」をお呼びください

CTR IMG