Comments (7)
Hi,
It seems to be a known issue with Leaflet, if its container size is changed or if it's not visible when the map is created. Calling map.invalidateSize()
resets the map display.
Here is an example to make it work with react-bootstrap:
class MapTabs extends React.Component {
constructor() {
super();
this.state = {
key: 1
};
}
onSelect(key) {
this.setState({key});
setTimeout(() => {
this.refs['map' + key].getLeafletElement().invalidateSize(false);
}, 300); // Adjust timeout to tab transition
}
render() {
return (
<TabbedArea activeKey={this.state.key} onSelect={this.onSelect.bind(this)}>
<TabPane eventKey={1} tab='Default Tab'>
<Map ref="map1" center={position} zoom={zoom} style={style}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>
<span>A pretty CSS3 popup.<br/>Easily customizable.</span>
</Popup>
</Marker>
</Map>
</TabPane>
<TabPane eventKey={2} tab='Map Tab'>
<Map ref="map2" center={position} zoom={zoom} style={style}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>
<span>A pretty CSS3 popup.<br/>Easily customizable.</span>
</Popup>
</Marker>
</Map>
</TabPane>
</TabbedArea>
);
}
}
The trick is to control the tabs from a parent component, this way you can access the relevant <Map>
via its ref
, and call invalidateSize()
after the tab is fully displayed. That's why there is a 300ms timeout before calling the function.
If the tabs transition has a different timing, you should adjust this timeout, making sure it's always superior or equal to the transition time, otherwise the map rendering would not be done properly.
from react-leaflet.
solution using hooks (and mobx sotre) in FunctionComponent :
parent tabs Component
interface IProps {
defaultKey? :string
}
export const TabsTemplate: React.FC<IProps> = observer(({defaultKey="charts"}) => {
const [activeKey] = useState(defaultKey);
const store = useStore();
store.isReadyToRenderMap = false;
return (
<Tabs defaultActiveKey={activeKey} id="main-tabs"
onSelect={(activeKey: any) => {
if (activeKey === "map") {
//map is renderd only when tab is shown
store.isReadyToRenderMap = true;
}
}}
>
<Tab eventKey="charts" title={"Charts"}>
<GroupByGraphsPanel />
</Tab>
<Tab eventKey="map" title={"Map"}>
<MyMap />
</Tab>
</Tabs>
)
})
child map Component
const MyMap : FunctionComponent<IProps> = observer(() => {
const mapRef = useRef<any>();
const store = useStore();
const reactMapCenter = toJS(store.mapCenter);
const WRAPPER_STYLES = { height: '500px', width: '100vw', maxWidth: '100%' };
const didMountRef = useRef(false)
useEffect(() => {
if (didMountRef.current) {
if (mapRef.current) {
//mapRef.current = true - like componentDidUpdate
//this event is fierd when parent tab is shown - help render map
mapRef.current.leafletElement.invalidateSize(false);
}
}
else didMountRef.current = true
})
return (
<div>
<Map ref={mapRef}
center={reactMapCenter}
zoom={13}
style={WRAPPER_STYLES}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<AccidentsMarkers />
</Map>
{store.isReadyToRenderMap?"":""}
</div>
)
})
from react-leaflet.
To anyone struggling with the map not rendering properly when using react-leaflet with reactstrap tabs, this is what worked for me.
<MapContainer
id="map-container"
style={{ height: "50vh" }}
center={[40, 20]}
zoom={2}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ResizeMap />
</MapContainer>```
const ResizeMap = () => {
const map = useMap();
const resizeObserver = new ResizeObserver(() => {
map.invalidateSize();
});
const container = document.getElementById("map-container");
resizeObserver.observe(container!);
return null;
};
Found this stackoverflow ANSWER helpful which initially didn't work because the whenReady prop will not let you use the Map instance as described in the answer.
Instead, <MapContainer />
will pass the Map instance to it's children elements as described in the React-leaflet docs
from react-leaflet.
Hi, thanks!
I have never had this use case so I don't know what can be the exact origin, can you setup a jsbin or something showing the issue please?
from react-leaflet.
Thanks for the quick response. It is a pretty niche problem! I'll try to reproduce it for you somewhere public.
from react-leaflet.
I'm afraid I don't know how to reproduce it in an environment like jsbin as I don't know how to get react-bootstrap & react-leaflet without npm. The code required for a simple demo is below:
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://fb.me/react-with-addons-0.13.3.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<!-- Leaflet Maps Styling -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css">
<meta charset="utf-8">
<title>Tabbed Map Example</title>
</head>
<body>
<div id="tab-container"></div>
<script type="text/javascript" src="demo.js"></script>
</body>
</html>
app.js
var React = require('react');
var TabbedArea = require('react-bootstrap/lib/TabbedArea');
var TabPane = require('react-bootstrap/lib/TabPane');
const position = [51.5072, -0.1275];
const style = { height: '400px' };
const zoom = 5;
const tabbedAreaInstance = (
<TabbedArea defaultActiveKey={1}>
<TabPane eventKey={1} tab='Default Tab'>
<Map center={position} zoom={zoom} style={style}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>
<span>A pretty CSS3 popup.<br/>Easily customizable.</span>
</Popup>
</Marker>
</Map>
</TabPane>
<TabPane eventKey={2} tab='Map Tab'>
<Map center={position} zoom={zoom} style={style}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position}>
<Popup>
<span>A pretty CSS3 popup.<br/>Easily customizable.</span>
</Popup>
</Marker>
</Map>
</TabPane>
</TabbedArea>
);
React.render(tabbedAreaInstance, document.getElementById('tab-container'));
browserify command
browserify app.js -t babelify --outfile demo.js
You'll need to npm install react-bootstrap
, react
and react-leaflet
. Sorry I couldn't make it easier. Does that seem reasonable?
The demo has a set up with two tabs. I've put maps in both tabs to show that it loads properly in the default tab but when you switch to the other tab the tiles do not load properly, even when you pan around a bit it seems confused.
I'm using Chrome 43 on Ubuntu.
I hope that is sufficient but please ask if there are details I've missed.
Michael
from react-leaflet.
Wow, thank you for investigating and for the explaining. Kind of you to give such a clear run down. I will attempt to integrate this approach into my set up.
I guess I'll close this ticket as there isn't really an action point for it. It is such an edge case that it doesn't seem worth trying to add to the documentation for react-leaflet itself.
Much appreciated!
from react-leaflet.
Related Issues (20)
- "Download All Assets" link is broken
- [question] Change Center of map if state changes
- [Question] Change z-index and styles of tooltip of React-Leaflet onMouseover
- [Question] React-leaflet does not let react-modal close on first click HOT 2
- Image shrinking when using ImageOverlay
- Marker with invalid lat, long values are shown in Antartica
- Map are don't have HoangSa and TruongSa islands belong to VIetNam by defaults
- Map rendered with missing parts HOT 8
- ESM packages (@react-leaflet/core) need to be imported.
- Iām interested in enhancing the documentation.
- BUG: Control Component event handling HOT 1
- How to add an additional layer?
- MapContainer whenReady doesn't receive target parameter from Leaflet HOT 1
- Problem with rendering OS Maps Leisure Layers HOT 1
- [Turbopack] Parsing css source code failed HOT 5
- Help please
- error rendering <Marker> component in react
- Prevent Vector Layer to automatic scale HOT 3
- Is everything okay with Nextjs v14.1.0 + React v18? Maps doesn't render HOT 4
- Get Distance Function? HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
š Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ššš
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ā¤ļø Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-leaflet.