![](/img/trans.png)
[英]How to use Leaflet's FeatureGroup with OverlappingMarkerSpiderfier in react-leaflet?
[英]Pointers on how to use leaflet's polyline in reactjs & react-leaflet
我對 React 和傳單很陌生。 我正在嘗試使用傳單在 React 的地圖上繪制一組可用的緯度和經度。 關於如何做到這一點的任何指示都會有所幫助。
我已經閱讀了來自https://react-leaflet.js.org 的關於 React 傳單的教程。 但我無法繼續。 任何幫助是極大的贊賞。 提前致謝。
我擁有的對象數據數組的示例:
data=[
{
from_lat: "12.92415",
from_long: "77.67229",
id: "132512",
to_lat: "12.92732",
to_long: "77.63575",
},
{
from_lat: "12.96691",
from_long: "77.74935",
id: "132513",
to_lat: "12.92768",
to_long: "77.62664",
}
]
您可以像這樣將數據存儲在狀態中:
state = {
...
data: [
{
from_lat: "12.92415",
from_long: "77.67229",
id: "132512",
to_lat: "12.92732",
to_long: "77.63575",
},
{
from_lat: "12.96691",
from_long: "77.74935",
id: "132513",
to_lat: "12.92768",
to_long: "77.62664",
}
]
};
然后迭代數據並返回一個 Polyline 實例,如下所示:
<Map
style={{ height: "100vh" }}
center={position}
zoom={this.state.zoom}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{this.state.data.map(({id, from_lat, from_long, to_lat, to_long}) => {
return <Polyline key={id} positions={[
[from_lat, from_long], [to_lat, to_long],
]} color={'red'} />
})}
</Map>
https://codesandbox.io/s/react-leaflet-polyline-hedzz
import {
FeatureGroup,
MapContainer,
Marker,
Polyline,
TileLayer
} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import L from "leaflet";
const CustomPoliLine = () => {
const mapRef = useRef();
const [center, setCenter] = useState({ lat: 36.460353, lng: 126.440674 });
const [map, setMap] = useState(null);
const pos = [
[36.460353, 126.440674],
[34.789594, 135.438084], //to jpn
[36.460353, 126.440674],
[55.410343, 37.902312], //to rus
[36.460353, 126.440674],
[40.085148, 116.552407] //to chi
];
return (
<div>
<MapContainer
style={{ height: "480px", width: "100%" }}
zoom={6}
center={center}
ref={mapRef}
whenReady={setMap}
scrollWheelZoom={true}
>
<FeatureGroup>
{pos?.map((mark, i) => (
<Marker key={i} position={mark} icon={customMarkerUserPos} />
))}
<Polyline positions={pos} color="red" />
</FeatureGroup>
<TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
</MapContainer>
</div>
);
};
export default CustomPoliLine;
export const customMarkerUserPos = new L.Icon({
iconUrl: "https://unpkg.com/leaflet@1.5.1/dist/images/marker-icon.png",
iconSize: [15, 20],
iconAnchor: [5, 20],
popupAnchor: [2, -40]
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.