我按照 React Locate on map 的回答,在 gatsby 开发模式下一切正常。但是如果我构建我的 gatsby 项目它会抛出一个 webpack 错误
“WebpackError: TypeError: Object(...) is not a function”.
如果我更改代码
export default withLeaflet(LocateControl);
到
export default withLeaflet(LocateControl);
构建有效,但我在浏览器中收到错误
“类型错误:this.props.leaflet 未定义”
import React, { Component } from "react";
import { withLeaflet } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
class LocateControl extends Component {
componentDidMount() {
const { options, startDirectly } = this.props;
const { map } = this.props.leaflet;
const lc = new Locate(options);
lc.addTo(map);
if (startDirectly) {
// request location update and set location
lc.start();
}
}
render() {
return null;
}
}
export default withLeaflet(LocateControl);
locate-plugin 应该可以工作,但现在构建不工作了。
我遇到了同样的问题,几个小时后这个解决方案对我有用:
locatecontrol.js
import { useEffect } from "react";
import { useLeaflet } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
export default function LocateControl() {
const { map } = useLeaflet();
useEffect(() => {
// geo locate props
const locateOptions = {
position: 'topright',
maxZoom: 19,
strings: {
title: 'Show me where I am, yo!'
},
onActivate: () => {} // callback before engine starts retrieving locations
}
const lc = new Locate(locateOptions);
// console.log(lc);
lc.addTo(map);
}, [map]);
return null;
}
导入到leaflet-map.js
import LocateControl from "./locatecontrol"
并在Map中使用LocateControl
<Map>
<LocateControl startDirectly/>
</Map>
我是 React 的新手,我不确定解决方案是否完全正确 - 但我还没有遇到错误(我们会看到 :))并且 gatsby 构建正常。
也许有人会想出更好的解决方案。
要使用 React-Leaflet 核心 API 创建带有
leaflet.locatecontrol
的位置控件,可以利用 createControlComponent
高级组件工厂功能.
import { createControlComponent } from '@react-leaflet/core';
import * as L from 'leaflet';
import 'leaflet.locatecontrol';
import 'leaflet.locatecontrol/dist/L.Control.Locate.css';
interface P extends L.ControlOptions {}
const { Locate } = L.Control;
function createLocateInstance(props: P) {
const instance = new Locate(props);
return instance;
}
export const LocateControl = createControlComponent(createLocateInstance);
<MapContainer
center={[38.9072, -77.0369]}
zoom={8}
zoomControl={false}
style={{ height: '100vh', width: '100%', padding: 0 }}
whenReady={() => {}}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{/*
Here is the custom control component.
Pass in any desired options as props to the component.
*/}
<LocateControl position="topright" />
</MapContainer>
别忘了您可能需要安装
@types/leaflet.locatecontrol
!