[英]why leaflet map doesn't render on react app
I included leaflet map with js
implementation instead of jsx
implementation but I have a problem as it overflows its scope.我在
js
实现中包含了传单地图,而不是jsx
实现,但是我遇到了一个问题,因为它超出了它的范围。
this is how I imported leaflet:这是我导入传单的方式:
import L from 'leaflet';
and implemented:并实施:
componentDidMount() {
// create map
this.map = L.map('map', {
center: [49.8419, 24.0315],
zoom: 16,
layers: [
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}),
]
});
}
and usage:和用法:
<div id={"map"} >
You have not added the leaflet css file in your index.html
.您尚未在
index.html
添加传单 css 文件。
For leaflet version 1.3.4
, add the following to index.html对于传单版本
1.3.4
,将以下内容添加到 index.html
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
In your map component css file, override the leaflet-container
class with desired height and width.在您的地图组件 css 文件中,使用所需的高度和宽度覆盖
leaflet-container
类。
.leaflet-container {
height: 600px;
width: 100%;
}
Once you have added that, use Map
and TileLayer
Components of react-leaflet
to render map.添加后,使用
react-leaflet
Map
和TileLayer
组件来渲染地图。
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer } from "react-leaflet";
import "./styles.css";
class App extends Component {
state = {
center: [51.505, -0.091],
zoom: 13
};
render() {
return (
<div>
<Map center={this.state.center} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
</Map>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can find working code here.您可以在此处找到工作代码。 https://codesandbox.io/s/2wnv7o1mlr
https://codesandbox.io/s/2wnv7o1mlr
Yeah you're missing the css file.是的,您缺少 css 文件。
incidentally this is not how you should be using react-leaflet
.顺便说一句,这不是您应该如何使用
react-leaflet
。 componentDidMount is not the place for doing what you're doing. componentDidMount 不是做你正在做的事情的地方。 Put that in the render like
把它放在渲染中
import { Map, TileLayer } from 'react-leaflet';
<Map>
<TileLayer url="'http://{s}.tile.osm.org/{z}/{x}/{y}.png'" />
</Map>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.