无法弄清楚如何将 GeometryUtil 与 React-Leaflet 一起使用
Trouble figuring out how to use GeometryUtil with React-Leaflet
我正在使用 JavaScript、React & Leaflet(+React-Leaflet 插件)构建应用程序。
我想获得离我的位置最近的标记的坐标,但我无法弄清楚如何将 GeometryUtil 插件与 React-Leaflet 一起使用。
我试过这段代码,但它 returns 一条错误消息。
const Map = ({ markers, center, zoom }) => {
/* My location. (Dummy data). */
const myLocation = [-40.5512, 69.9454];
/* Saving map instance to state: */
const [map, setMap] = useState(null);
*/ Using GeometryUtil. Error occurs here. */
let closest_latlng = L.GeometryUtil.closest(map, markers, myLocation);
console.log(closest_latlng);
return (
<MapContainer
className="map"
center={center}
zoom={zoom}
scrollWheelZoom={false}
whenCreated={(map) => setMap(map)}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{markers && (
<>
{markers.map((marker, idx) => (
<AllMarkers key={idx} marker={marker} />
))}
</>
)}
</MapContainer>
);
};
export default Map;
错误信息:
未处理的拒绝 (TypeError):无法读取未定义的属性(读取 'closest')。
问题在于您导入 geometryutil 包的方式。像这样尝试:
import 'leaflet-geometryutil';
然后你应该 L.GeometryUtil 在 L 可用的任何地方可用。确保此导入发生在某些根级别文件中,例如 index.js 或 app.js,以便在您调用 L.GeometryUtil 函数时,它已经被导入。
或者,在您要使用它的文件中,
import GeometryUtil from "leaflet-geometryutil";
// or
import * as GeometryUtil from "leaflet-geometryutil";
let closest_latlng = GeometryUtil.closest(map, markers, myLocation); // no L.GeometryUtil
我正在使用 JavaScript、React & Leaflet(+React-Leaflet 插件)构建应用程序。 我想获得离我的位置最近的标记的坐标,但我无法弄清楚如何将 GeometryUtil 插件与 React-Leaflet 一起使用。
我试过这段代码,但它 returns 一条错误消息。
const Map = ({ markers, center, zoom }) => {
/* My location. (Dummy data). */
const myLocation = [-40.5512, 69.9454];
/* Saving map instance to state: */
const [map, setMap] = useState(null);
*/ Using GeometryUtil. Error occurs here. */
let closest_latlng = L.GeometryUtil.closest(map, markers, myLocation);
console.log(closest_latlng);
return (
<MapContainer
className="map"
center={center}
zoom={zoom}
scrollWheelZoom={false}
whenCreated={(map) => setMap(map)}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{markers && (
<>
{markers.map((marker, idx) => (
<AllMarkers key={idx} marker={marker} />
))}
</>
)}
</MapContainer>
);
};
export default Map;
错误信息: 未处理的拒绝 (TypeError):无法读取未定义的属性(读取 'closest')。
问题在于您导入 geometryutil 包的方式。像这样尝试:
import 'leaflet-geometryutil';
然后你应该 L.GeometryUtil 在 L 可用的任何地方可用。确保此导入发生在某些根级别文件中,例如 index.js 或 app.js,以便在您调用 L.GeometryUtil 函数时,它已经被导入。
或者,在您要使用它的文件中,
import GeometryUtil from "leaflet-geometryutil";
// or
import * as GeometryUtil from "leaflet-geometryutil";
let closest_latlng = GeometryUtil.closest(map, markers, myLocation); // no L.GeometryUtil