Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render mapbox vector tiles inside react-leaflet?

Is there a way to use vector tiles from react-leaflet?

I am aware of Leaflet.VectorGrid, but it is not written for react-leaflet?

like image 234
Bjorn Reppen Avatar asked Mar 13 '17 13:03

Bjorn Reppen


2 Answers

For react-leaflet v2, export the MapBoxGLLayer component wrapped with HOC withLeaflet() to get it working.

Steps:

1.Install mapbox-gl-leaflet.

npm i mapbox-gl-leaflet 

2.Add mapbox-gl js and css to index.html

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.51.0/mapbox-gl.css' rel='stylesheet' />  

3.Add this component.

import L from "leaflet";
import {} from "mapbox-gl-leaflet";
import PropTypes from "prop-types";
import { GridLayer, withLeaflet } from "react-leaflet";

class MapBoxGLLayer extends GridLayer {
  createLeafletElement(props) {
    return L.mapboxGL(props);
  }
}

/*
* Props are the options supported by Mapbox Map object
* Find options here:https://www.mapbox.com/mapbox-gl-js/api/#new-mapboxgl-map-options-
*/
MapBoxGLLayer.propTypes = {
  accessToken: PropTypes.string.isRequired,
  style: PropTypes.string
};

MapBoxGLLayer.defaultProps = {
  style: "mapbox://styles/mapbox/streets-v9"
};

export default withLeaflet(MapBoxGLLayer);   

4.Use the MapBoxGLLayer component.

class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <MapBoxGLLayer
            accessToken={MAPBOX_ACCESS_TOKEN}
            style="mapbox://styles/mapbox/streets-v9"
          />
        </Map>
      </div>
    );
  }
}

Find the working code here (Add your own mapbox token): https://codesandbox.io/s/ooypokn26y

like image 107
Murli Prajapati Avatar answered Oct 11 '22 17:10

Murli Prajapati


There are some really nice vector tiles examples in this react-leaflet issue (mapbox-gl example reproduced below).

// @flow

import L from 'leaflet'
import {} from 'mapbox-gl-leaflet'
import {PropTypes} from 'react'
import { GridLayer } from 'react-leaflet'

export default class MapBoxGLLayer extends GridLayer {
  static propTypes = {
    opacity: PropTypes.number,
    accessToken: PropTypes.string.isRequired,
    style: PropTypes.string,
    zIndex: PropTypes.number,
  }

  createLeafletElement(props: Object): Object {
    return L.mapboxGL(props)
  }
}

and the usage of the above component:

<Map>
  <MapBoxGLLayer
    url={url}
    accessToken={MAPBOX_ACCESS_TOKEN}
    style='https://style.example.com/style.json'
  />
</Map>

NOTE: you may also need to npm install mapbox-gl and import that library and assign into to the global window.mapboxgl = mapboxgl to avoid issues with mapboxgl being undefined.

like image 39
lando Avatar answered Oct 11 '22 17:10

lando