Reputation: 453
I'm trying to use Leaflet on a React project. My goal is actually very basic: just display a openstreetMap layer (without markers or stuff)
Here is my code:
import React, { Component } from 'react';
import L from 'leaflet';
class MyMap extends Component {
constructor(){
super();
this.state ={
map:null,
};
}
componentDidMount() {
var map = L.map('map', {
minZoom: 2,
maxZoom: 20,
layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})],
attributionControl: false,
});
return this.setState({
map: map
});
}
render() {
return (
<div id='map'> </div>
);
}
}
ReactDOM.render(
<MyMap />,
document.getElementById('root')
);
Each time I have the save problem to display the map: it looks like this: (not all tiles displayed and they are superpositions issues): Screenshot
Is someone face to this problem or have any solutions ?
Thank you for your help
Upvotes: 1
Views: 1051
Reputation: 18546
First, make sure that you've loaded in Leaflet's stylesheet:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
The shuffle of the tiles happens because either the stylesheet not loaded yet or Leaflet is executed after React is actually rendering the map target. What we can do is add a timeout for the initialization:
class MyMap extends React.Component {
constructor() {
super();
this.state ={
map: null,
};
}
componentDidMount() {
setTimeout(() => {
var map = L.map('map', {
minZoom: 2,
maxZoom: 20,
layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})],
attributionControl: false,
});
map.fitWorld();
return this.setState({
map: map
});
}, 100)
}
render() {
return <div id="map" style={{ height: 300 }}></div>;
}
}
ReactDOM.render(
<MyMap />,
document.getElementById('View')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<div id="View"></div>
Upvotes: 2