使React-Leaflet能够离线使用

6
我一直在使用react-leaflet库,目前它运行良好。
现在我想让网站尽可能预加载瓦片,以便该Web应用程序(也是PWA)可以在没有互联网的情况下使用。
我找到了一些现有的解决方案(虽然不是专门针对react的)。

这是我迄今为止尝试过的 - 使用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:
          '&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>
    );
  }
}

这个例子的错误信息说,地图已经被初始化了。 地图容器已经被初始化。 有没有办法让一个现有的解决方案与react-leaflet兼容?或者有更好的方法为PWA添加离线模式?
非常感谢任何见解。提前致谢!

这个回答解决了你的问题吗?在React中使用leaflet.offline? - Tmfwang
3个回答

1

如果你使用的是V1,那么你需要扩展react-leafletTileLayer类。这很简单。

这里有一个示例:https://jsfiddle.net/q2v7t59h/1965/

目前它在使用localforage时出现了问题(以前从未使用过),所以你需要修复它。但是定义createLeafletElement函数的关键仍然是正确的。

如果你正在使用react-leaflet V2,那么扩展TileLayer会更加麻烦。阅读https://github.com/PaulLeCam/react-leaflet/issues/506,你应该能够解决它。如果你认为它值得关注,请投票支持该问题。


你是否找到了在React-Leaflet v2中使用Leaflet-Offline的解决方案? - Geek Junior
我在使用OfflineTileLayer类时遇到了以下错误:未捕获的类型错误:超级表达式必须为null或函数 - Biaspoint
1
@Biaspoint,这个错误听起来像是你试图扩展一个不可扩展的react-leaflet组件。你可以尝试使用我的分支'react-leaflet-extendable',但我已经好几年没有更新它了,所以你可能需要将其基于react-leaflet进行重置。 - jbccollins

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

-2

你可以在leaflet上方添加另一个带有某个id的div

并使用该id将其添加到地图中 例如:const map = L.map('map-id'); 而不是const map = L.map('map');componentDidMount中实现


你能否编辑你的回答,使用正确的格式来呈现代码块。 - Cray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接