javascript - 如何在 React-Leaflet 3 中使用 Leaflet Routing Machine?
问题描述
react-leaflet 2.8.0 中的旧方法是使用MapLayer
and withLeaflet
。
但现在在反应传单中:
MapLayer
从第 3 版起withLeaflet
已弃用。
我正在尝试掌握核心文档:https ://react-leaflet.js.org/docs/core-introduction
但以下不起作用,我明白了
提供的对象不是图层。
import React, { Component, useEffect } from "react";
import { useLeafletContext, leafletElement, createLayerComponent } from '@react-leaflet/core'
import { MapContainer, TileLayer, useMap } from "react-leaflet";
import Leaflet from "leaflet";
import "leaflet-routing-machine";
function Routing(props) {
const context = useLeafletContext();
useEffect(() =>
{
let routing = createLayerComponent(Leaflet.Routing.control(
{
waypoints: [
Leaflet.latLng(33.52001088075479, 36.26829385757446),
Leaflet.latLng(33.50546582848033, 36.29547681726967)
],
lineOptions: {
styles: [{ color: "#6FA1EC", weight: 4 }]
},
show: false,
addWaypoints: false,
routeWhileDragging: true,
draggableWaypoints: true,
fitSelectedRoutes: true,
showAlternatives: false
}), )
const container = context.layerContainer || context.map
container.addLayer(routing)
return () => {
container.removeLayer(routing)
}
})
return null;
}
function MapComponent() {
return (
<MapContainer center={[33.5024, 36.2988]} zoom={14} >
<TileLayer url="https://api.maptiler.com/maps/ch-swisstopo-lbm-dark/256/{z}/{x}/{y}.png?key=gR2UbhjBpXWL68Dc4a3f" />
<Routing />
</MapContainer>
);
}
export default MapComponent;
解决方案
您正在使用createLayerComponent
,但路由机实际上是一个控件。使用createControlComponent
.
我还建议将其作为一个单独的自定义组件,如文档中所述,而不是将其放入 useEffect 中。文档很难。随意阅读如何在 react-leaflet v3 中扩展 TileLayer 组件?看看这是否有助于理解如何使用 react-leaflet v3 制作自定义组件。
以下是你的做法:
import L from "leaflet";
import { createControlComponent } from "@react-leaflet/core";
import "leaflet-routing-machine";
const createRoutineMachineLayer = (props) => {
const instance = L.Routing.control({
waypoints: [
L.latLng(33.52001088075479, 36.26829385757446),
L.latLng(33.50546582848033, 36.29547681726967)
],
...otherOptions
});
return instance;
};
const RoutingMachine = createControlComponent(createRoutineMachineLayer);
export default RoutingMachine;
工作代码沙盒
推荐阅读
- java - 如何在 java 命名查询中编写区分大小写的查询
- sql - 当我在 sqlite3 中使用 SUM(CASE WHEN .... THEN "column_name") 时,我得到了意想不到的结果
- ios - 如何更改 iPhone 部署目标
- reactjs - 基于角色的授权的正确位置
- azure-devops - Jira 与 AzureDevOps 板
- php - Laravel 6 用户登录时记住我的令牌错误
- python - 网页抓取:使用 bs4 抓取数据时获取“\n”标签
- c# - 如何实现一个类来决定是好还是坏请求
- laravel - 为什么 Laravel 急切加载不适用于对象函数?
- javascript - 为什么在 JSX 中只能使用表达式,不能使用语句?