google-maps-route-creator
Version:
Google Maps Route Creator is a tool that helps you to create a route on Google Maps and calculate the distance between the points.
425 lines (421 loc) • 13.3 kB
JavaScript
// src/lib/mapComponent.tsx
import {
GoogleMap,
LoadScript,
TrafficLayer,
Marker,
Polyline
} from "@react-google-maps/api";
import React2, { useEffect, useState } from "react";
// src/lib/marker.jsx
var CustomMaker = () => {
return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
"svg",
{
height: "24",
version: "1.1",
width: "24",
xmlns: "http://www.w3.org/2000/svg",
"xmlns:cc": "http://creativecommons.org/ns#",
"xmlns:dc": "http://purl.org/dc/elements/1.1/",
"xmlns:rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
},
/* @__PURE__ */ React.createElement("g", { transform: "translate(0 -1028.4)" }, /* @__PURE__ */ React.createElement(
"path",
{
d: "m12.031 1030.4c-3.8657 0-6.9998 3.1-6.9998 7 0 1.3 0.4017 2.6 1.0938 3.7 0.0334 0.1 0.059 0.1 0.0938 0.2l4.3432 8c0.204 0.6 0.782 1.1 1.438 1.1s1.202-0.5 1.406-1.1l4.844-8.7c0.499-1 0.781-2.1 0.781-3.2 0-3.9-3.134-7-7-7zm-0.031 3.9c1.933 0 3.5 1.6 3.5 3.5 0 2-1.567 3.5-3.5 3.5s-3.5-1.5-3.5-3.5c0-1.9 1.567-3.5 3.5-3.5z",
fill: "#c0392b"
}
), /* @__PURE__ */ React.createElement(
"path",
{
d: "m12.031 1.0312c-3.8657 0-6.9998 3.134-6.9998 7 0 1.383 0.4017 2.6648 1.0938 3.7498 0.0334 0.053 0.059 0.105 0.0938 0.157l4.3432 8.062c0.204 0.586 0.782 1.031 1.438 1.031s1.202-0.445 1.406-1.031l4.844-8.75c0.499-0.963 0.781-2.06 0.781-3.2188 0-3.866-3.134-7-7-7zm-0.031 3.9688c1.933 0 3.5 1.567 3.5 3.5s-1.567 3.5-3.5 3.5-3.5-1.567-3.5-3.5 1.567-3.5 3.5-3.5z",
fill: "#e74c3c",
transform: "translate(0 1028.4)"
}
))
));
};
var marker_default = CustomMaker;
// src/lib/mapComponent.tsx
var MapComponent = ({
RoutePoint,
GoogleResult,
markerOnClick,
addNewRoutePoint,
googleMapsApiKey,
justDrawRoute
}) => {
const [mapInstance, setMapInstance] = useState(null);
const [route, setRoute] = useState([]);
const [hoverState, setHoverState] = useState({});
const [error, setError] = useState(null);
const [Points, setPoints] = useState([]);
const [ggRoute, setGGRoute] = useState([]);
useEffect(() => {
console.log("GG Route:", ggRoute);
if (ggRoute.length === Points.length) {
GoogleResult(ggRoute);
}
}, [ggRoute]);
useEffect(() => {
setRoute([]);
setPoints(RoutePoint);
}, [RoutePoint]);
useEffect(() => {
if (mapInstance) {
if (justDrawRoute) {
justDrawRoute.map((item, i) => {
setRoute((prev) => prev.length == 0 ? [item] : [...prev, item]);
});
} else {
Points.map((item, i) => {
fetchDirections(item, i);
});
}
}
}, [Points]);
const containerStyle = {
width: "100%",
height: "100%"
};
const center = {
lat: 38.97271048516351,
lng: 35.49849134823012
};
const fetchDirections = async (c, i) => {
const directionsOptions2 = { ...c };
let p = { ...c };
delete p.start.data;
delete p.end.data;
try {
p.waypoints = p.waypoints.map((item) => {
return { location: item.location, stopover: item.stopover };
});
} catch (error2) {
console.log("Error:", p.waypoints);
}
const directionsOptions = {
origin: p.start,
destination: p.end,
travelMode: "DRIVING",
waypoints: p.waypoints,
drivingOptions: {
departureTime: new Date(Date.now()),
trafficModel: "optimistic"
},
optimizeWaypoints: false
};
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i2 = 0; i2 < 6; i2++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
const directionsService = new google.maps.DirectionsService();
const rt = [];
await directionsService.route(
directionsOptions,
(result, status) => {
if (status === "OK") {
const routeData = result?.routes[0].legs.map(
(leg, index) => {
const random = getRandomColor();
let icon = "";
let type = "";
let list = directionsOptions2.waypoints;
if (typeof directionsOptions2.waypoints !== void 0 && directionsOptions2.waypoints?.length > 0) {
icon = directionsOptions2.waypoints[index]?.icon;
type = directionsOptions2.waypoints[index]?.type;
}
return {
route: leg.steps.map((step, i2) => ({
path: step.path,
trafficDuration: step.duration_in_traffic?.value || "normal"
})),
isHovered: false,
icon: icon || marker_default,
type: type || "Yok",
cords: {
lat: leg.start_location.lat(),
lng: leg.start_location.lng()
},
pathColor: result.routes[0].legs.length - 1 == index ? "rgba(229, 58, 54, 0.50)" : "rgba(31, 135, 227, 0.75)"
};
}
);
const setRouteObject = {
route: routeData,
start: p.start,
end: p.end,
isHovered: false,
markerPosition: directionsOptions2,
googleResult: result
};
setGGRoute((prev) => {
if (prev.find((e) => e.index === i) === void 0) {
return [...prev, { index: i, data: setRouteObject }];
}
return prev;
});
setRoute(
(prev) => prev.length == 0 ? [setRouteObject] : [...prev, setRouteObject]
);
}
}
);
};
useEffect(() => {
setRoute([]);
if (mapInstance) {
if (justDrawRoute) {
justDrawRoute.map((item, i) => {
setRoute((prev) => prev.length == 0 ? [item] : [...prev, item]);
});
} else {
Points.map((item, i) => {
fetchDirections(item, i);
});
}
}
}, [mapInstance]);
useEffect(() => {
}, [route]);
const [activeMarker, setActiveMarker] = useState(null);
const handleMarkerClick = (id) => {
setActiveMarker(id);
};
const handleInfoWindowClose = () => {
setActiveMarker(null);
};
const handleMapOnLoad = (Instance) => {
setMapInstance(Instance);
};
const [mouseActivity, setMouseActivity] = useState(null);
const handleMouseOver = (index) => {
setMouseActivity(index);
};
const handleDragPath = (e, c) => {
addNewRoutePoint(
{
location: { lat: e.latLng.lat(), lng: e.latLng.lng() },
stopover: false
},
e,
c
);
};
return /* @__PURE__ */ React2.createElement(LoadScript, { googleMapsApiKey }, /* @__PURE__ */ React2.createElement(
GoogleMap,
{
mapContainerStyle: containerStyle,
center: {
lat: 38.97271048516351,
lng: 35.49849134823012
},
zoom: 6,
options: {
fullscreenControl: false,
mapTypeControl: false,
zoomControl: true,
streetViewControl: false,
scaleControl: false
},
onLoad: handleMapOnLoad
},
/* @__PURE__ */ React2.createElement(TrafficLayer, null),
route && route.map((segment, index, all) => /* @__PURE__ */ React2.createElement("div", { key: "Route_" + index }, segment.route.map((s, i) => /* @__PURE__ */ React2.createElement("div", { key: "Route_variant_" + i }, s.route.map((r, j) => {
let opt = {
strokeColor: r.traffic === "high" ? "red" : s.pathColor,
strokeOpacity: 0.8,
strokeWeight: mouseActivity == j ? 9 : 6,
draggable: false,
geodesic: true,
edittable: true
};
const dotIcon = {
path: "M 0, 0 m -5, 0 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0",
fillColor: "#333333",
fillOpacity: 1,
strokeWeight: 0,
scale: 0.7
};
return /* @__PURE__ */ React2.createElement("div", { key: "Plyline_div_" + index + "_" + i + "_" + j }, /* @__PURE__ */ React2.createElement(
Polyline,
{
key: "Plyline_" + index + "_" + i + "_" + j,
path: r.path,
options: opt,
onMouseOver: (e) => {
},
onMouseOut: (e) => {
}
}
), /* @__PURE__ */ React2.createElement(
Marker,
{
position: r.path[Math.ceil(r.path.length / 3) - 1],
icon: dotIcon,
draggable: true,
onDragEnd: (e) => {
handleDragPath(e, index);
}
}
));
}))))),
route && route.map((s, index) => /* @__PURE__ */ React2.createElement("div", { key: "RoutePoint_" + index }, s?.markerPosition.end && /* @__PURE__ */ React2.createElement(
Marker,
{
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_finish",
position: s?.markerPosition.end,
icon: {
url: s?.markerPosition.end.icon || marker_default,
scaledSize: new google.maps.Size(60, 60)
},
onClick: () => markerOnClick(s)
}
), s?.markerPosition.waypoints.map((w, i, l) => /* @__PURE__ */ React2.createElement(
Marker,
{
key: "PlylineMarker_" + i + "_RoutePoint_",
position: w.location,
icon: {
url: w.icon || marker_default,
scaledSize: new google.maps.Size(40, 60)
},
onClick: () => markerOnClick(w)
}
)), s?.markerPosition.start && /* @__PURE__ */ React2.createElement(
Marker,
{
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_start",
position: s?.markerPosition.start,
icon: {
url: s?.markerPosition.start.icon,
scaledSize: new google.maps.Size(60, 60)
},
onClick: () => markerOnClick(s)
}
))),
error && /* @__PURE__ */ React2.createElement("div", null, error)
));
};
var mapComponent_default = MapComponent;
// src/lib/MapSelectLocation.tsx
import {
GoogleMap as GoogleMap2,
LoadScript as LoadScript2,
Marker as Marker2
} from "@react-google-maps/api";
import React3 from "react";
import { useEffect as useEffect2, useRef, useState as useState2 } from "react";
var MapSelectLocation = ({
address,
onResult
}) => {
const mapRef = useRef(null);
const [mark, setMark] = useState2();
const containerStyle = {
width: "100%",
height: "400px",
cursor: "crosshair !important"
};
const center = {
lat: 38.97271048516351,
lng: 35.49849134823012
};
const [centerCoord, setCenterCoord] = useState2({
lat: 38.97271048516351,
lng: 35.49849134823012
});
const [resultsCoords, setResultCoords] = useState2();
const [selectedAddress, setSelectedAddress] = useState2(null);
useEffect2(() => {
setSelectedAddress(address);
}, [address]);
const handleMapOnLoad = (map) => {
mapRef.current = map;
if (selectedAddress) {
const geocoding = new google.maps.Geocoder();
geocoding.geocode({ address: selectedAddress }, (results, status) => {
console.log(results);
if (results && results[0] !== void 0) {
setCenterCoord({
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
});
setMark({
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
});
setResultCoords({
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
});
}
});
}
};
useEffect2(() => {
onResult(resultsCoords);
}, [resultsCoords]);
const handleClick = (e) => {
const cords = {
lat: e.latLng.lat(),
lng: e.latLng.lng()
};
setResultCoords({ lat: e.latLng.lat(), lng: e.latLng.lng() });
setCenterCoord(cords);
setMark(cords);
};
const handleCenterChanged = () => {
if (mapRef.current) {
const newCenter = mapRef.current?.getCenter();
const newLat = newCenter.lat();
const newLng = newCenter.lng();
if (newLat !== centerCoord.lat || newLng !== centerCoord.lng) {
setCenterCoord({
lat: newCenter.lat(),
lng: newCenter.lng()
});
}
}
};
useEffect2(() => {
}, [mark]);
return /* @__PURE__ */ React3.createElement("div", { className: "w-full h-full" }, /* @__PURE__ */ React3.createElement(
LoadScript2,
{
googleMapsApiKey: process.env.NEXT_PUBLIC_REACT_APP_GOOGLE_MAPS_API_KEY
},
/* @__PURE__ */ React3.createElement(
GoogleMap2,
{
mapContainerStyle: containerStyle,
center: centerCoord,
zoom: 6,
options: {
zoomControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
draggable: true,
draggableCursor: "crosshair",
draggingCursor: "grab",
fullscreenControl: false,
mapTypeControl: false,
streetViewControl: false,
scaleControl: false
},
onClick: handleClick,
onLoad: handleMapOnLoad
},
mark && /* @__PURE__ */ React3.createElement(Marker2, { position: mark })
)
));
};
export {
mapComponent_default as MapComponent,
MapSelectLocation
};