使react-leaflet可以离线使用

时间:2018-10-15 05:47:10

标签: javascript reactjs leaflet offline react-leaflet

我一直在使用react-leaflet库,到目前为止它运行良好。

现在,我希望网站尽可能多地预加载图块,以便可以在不使用互联网的情况下使用Web应用程序(也是PWA)。

我找到了一些现有的解决方案(尽管不专门用于反应)

这是我到目前为止尝试过的-使用传单离线

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:
          '&copy; <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="&copy; <a href=&quot;https://osm.org/copyright&quot;>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>
    );
  }
}

此示例出现错误,表明地图已经初始化

Map container is already initialized.

是否有一种方法可以使现有解决方案与react-leaflet完美配合?还是有更好的方法为PWA添加脱机模式?

任何见识将受到高度赞赏。预先感谢!

3 个答案:

答案 0 :(得分:1)

是的,您需要扩展react-leaflet的{​​{1}}类。 如果您使用的是V1,则非常简单。 这是一个小提琴:https://jsfiddle.net/q2v7t59h/1965/ 目前,它在TileLayer用法(以前从未使用过)上中断了,因此您必须对其进行修复。但是定义localforage函数的症结仍然是正确的。

如果您使用的是createLeafletElement V2,那么扩展react-leaflet会比较麻烦。通读https://github.com/PaulLeCam/react-leaflet/issues/506,您应该可以弄清楚。哦,如果您认为值得关注,请对该问题进行投票。

答案 1 :(得分:0)

您可以在传单上方添加另一个具有某些ID的div

并使用该ID添加到地图 即。 const map = L.map('map-id'); 代替const map = L.map('map');componentDidMount

答案 2 :(得分:-1)

map.remove()之前添加offlineLayer.addTo(map)