The*_*heo 6 javascript offline leaflet reactjs react-leaflet
我一直在使用react-leaflet库,到目前为止它运行良好。
现在我希望网站预加载尽可能多的图块,以便网络应用程序(也是 PWA)可以在没有互联网的情况下使用。
我找到了一些现有的解决方案(虽然不是专用于反应)
这是我到目前为止所尝试过的 - 使用 leaflet-offline
import React from 'react';
import 'leaflet-offline';
import {
Map as LeafletMap,
TileLayer,
CircleMarker,
Marker,
Popup,
} from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
import localforage from 'localforage';
const defaultCoords = {
latitude: 0,
longitude: 0,
};
export class MapPage extends React.Component {
constructor(props) {
super(props);
this.map = React.createRef();
}
componentDidMount() {
const map = L.map('map');
const offlineLayer = L.tileLayer.offline(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
localforage,
{
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
minZoom: 5,
maxZoom: 20,
crossOrigin: true,
},
);
// offlineLayer.addTo(this.map); // tried to add to the reference, didn't work
offlineLayer.addTo(map);
}
render() {
const { latitude, longitude } = this.props.coords || defaultCoords;
return (
<LeafletMap
center={this.props.initialLocation}
zoom={16}
// ref={this.map} // tried referencing it also, didn't work
id="map"
>
<TileLayer
attribution="© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors"
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<CircleMarker center={[latitude, longitude]}>
<Popup>You are here!</Popup>
</CircleMarker>
<Marker
icon={markerIcon}
position={newPerson.location || this.props.initialLocation}
draggable
onDragEnd={this.props.handleNewPersonPositionChange}
/>
</LeafletMap>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这个例子有错误说,地图已经初始化
Map container is already initialized.
有没有一种方法可以使现有的解决方案与反应传单很好地配合?或者有更好的方法为 PWA 添加离线模式吗?
任何见解都将受到高度赞赏。提前致谢!
是的,你需要延长react-leaflet课程TileLayer。如果您使用的是 V1,那就非常简单了。这是一个小提琴: https: //jsfiddle.net/q2v7t59h/1965/
目前它正在破坏localforage使用(以前从未使用过),所以你必须修复它。但定义函数的关键createLeafletElement仍然是正确的。
如果您使用的是react-leafletV2,那么扩展TileLayer会有点痛苦。通读https://github.com/PaulLeCam/react-leaflet/issues/506你应该能够弄清楚。哦,如果您认为该问题值得关注,请投票。
| 归档时间: |
|
| 查看次数: |
3793 次 |
| 最近记录: |