This commit is contained in:
Андрей Дувакин 2024-10-05 17:19:36 +05:00
parent 5ceba75b92
commit 2931de97ef

View File

@ -2,12 +2,21 @@ import React, { useState, useEffect } from "react";
import { getDeliveryAccessories } from "../api.jsx";
import { useParams } from "react-router-dom";
import { getCoordinates } from "../geocoder.jsx";
import {
MapContainer,
TileLayer,
Marker,
Popup,
Polyline,
} from "react-leaflet";
import polyline from "@mapbox/polyline";
const DeliveryOrderDetails = () => {
const { id: deliveryOrderId } = useParams();
const [deliveryAccessories, setDeliveryAccessories] = useState([]);
const [loading, setLoading] = useState(true);
const [coordinates, setCoordinates] = useState([]);
const [route, setRoute] = useState([]);
useEffect(() => {
fetchDeliveryAccessories();
@ -25,6 +34,22 @@ const DeliveryOrderDetails = () => {
})
);
setCoordinates(coords);
if (coords.length > 1) {
const waypoints = coords
.map(({ longitude, latitude }) => `${longitude},${latitude}`)
.join(";");
const routeUrl = `https://router.project-osrm.org/route/v1/driving/${waypoints}?overview=full`;
const response = await fetch(routeUrl);
const data = await response.json();
if (data.routes && data.routes.length > 0) {
const geometry = data.routes[0].geometry;
const decodedRoute = polyline.decode(geometry);
setRoute(decodedRoute);
}
}
} catch (error) {
console.error("Ошибка при загрузке доставок:", error);
} finally {
@ -39,21 +64,46 @@ const DeliveryOrderDetails = () => {
<span className="visually-hidden">Загрузка доставок...</span>
</div>
) : (
<ul>
{deliveryAccessories.map((accessory) => {
const coord = coordinates.find(
(c) => c.city === accessory.city_name
);
return (
<li key={accessory.id}>
Доставка: {accessory.name} (Город: {accessory.city_name},
Координаты:{" "}
{coord ? `${coord.latitude}, ${coord.longitude}` : "Не найдены"}
)
</li>
);
})}
</ul>
<div>
<ul>
{deliveryAccessories.map((accessory) => {
const coord = coordinates.find(
(c) => c.city === accessory.city_name
);
return (
<li key={accessory.id}>
Доставка: {accessory.name} (Город: {accessory.city_name},
Координаты:{" "}
{coord
? `${coord.latitude}, ${coord.longitude}`
: "Не найдены"}
)
</li>
);
})}
</ul>
{coordinates.length > 0 && (
<MapContainer
center={[coordinates[0].latitude, coordinates[0].longitude]}
zoom={5}
style={{ height: "400px", width: "100%" }}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
/>
{coordinates.map((coord, index) => (
<Marker
key={index}
position={[coord.latitude, coord.longitude]}
>
<Popup>{coord.city}</Popup>
</Marker>
))}
{route.length > 0 && <Polyline positions={route} color="blue" />}
</MapContainer>
)}
</div>
)}
</div>
);