Skip to content

Instantly share code, notes, and snippets.

@fab1an
Last active January 10, 2022 03:50
Show Gist options
  • Save fab1an/f040edbd939989d3a2557f15d2b9ee02 to your computer and use it in GitHub Desktop.
Save fab1an/f040edbd939989d3a2557f15d2b9ee02 to your computer and use it in GitHub Desktop.
React / Leaflet combination
export default class GeoJsonMapLayer extends React.Component {
render() {
return (
<div>
</div>
);
}
componentWillUnmount() {
if (this.layer) {
this.props.layerParent.removeLayer(this.layer)
}
}
componentDidMount() {
this.componentDidUpdate();
}
componentDidUpdate() {
if (this.layer) {
this.props.layerParent.removeLayer(this.layer);
}
this.layer = Leaflet.geoJson(this.props, {
style: {
fill: false,
stroke: false
},
}).addTo(this.props.layerParent);
}
}
import React from 'react';
import _ from "lodash";
import Leaflet from 'leaflet';
import "leaflet/dist/leaflet.css";
import GeoJsonMapLayer from "./GeoJsonMapLayer";
export default class LeafletMap extends React.Component {
constructor(props) {
super(props);
this.layerParent = Leaflet.layerGroup();
}
render() {
return (
<div ref="mapContainer">
{_.map(this.props.layers, layer =>
<GeoJsonMapLayer {...layer}
key={layer.properties.code}
layerParent={this.layerParent}
/>
)}
</div>
);
}
componentDidMount() {
this.map = Leaflet.map(this.refs.mapContainer, {
zoom: MINZOOM,
minZoom: MINZOOM,
maxZoom: MAXZOOM,
center: CENTER,
maxBounds: MAXBOUNDS,
attributionControl: false,
doubleClickZoom: false,
layers: [
Leaflet.tileLayer(`http://api.tiles.mapbox.com/v3/${MAPBOX_MAPID}/{z}/{x}/{y}.png`),
this.layerParent,
],
});
}
componentWillUnmount() {
this.map.remove();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment