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.
440 lines (436 loc) • 14.1 kB
JavaScript
// src/lib/mapComponent.tsx
import {
GoogleMap,
LoadScript,
TrafficLayer,
Polyline
} from "@react-google-maps/api";
import React2, { useEffect, useState } from "react";
// src/lib/marker.tsx
import React from "react";
import { OverlayView } from "@react-google-maps/api";
// src/lib/mapComponent.tsx
import { OverlayView as OverlayView2 } from "@react-google-maps/api";
var MapComponent = ({
RoutePoint,
GoogleResult,
markerOnClick,
addNewRoutePoint,
googleMapsApiKey,
justDrawRoute,
CustomMarkers,
polylineOptions
}) => {
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(() => {
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 = void 0;
let type = "";
let color = "";
let list = directionsOptions2.waypoints;
if (index === 0) {
icon = directionsOptions2.waypoints[index + 1]?.icon;
type = directionsOptions2.waypoints[index + 1]?.type;
color = directionsOptions2.waypoints[index + 1]?.color;
}
if (index === result?.routes[0].legs.length - 1) {
icon = directionsOptions2.waypoints[index - 1]?.icon;
type = directionsOptions2.waypoints[index - 1]?.type;
color = directionsOptions2.waypoints[index - 1]?.color;
}
if (directionsOptions2.waypoints[index + 1]?.color === void 0) {
icon = directionsOptions2.waypoints[1]?.icon;
type = directionsOptions2.waypoints[1]?.type;
color = directionsOptions2.waypoints[1]?.color;
}
if (typeof directionsOptions2.waypoints !== void 0 && directionsOptions2.waypoints?.length > 0) {
icon = directionsOptions2.waypoints[index + 1]?.icon;
type = directionsOptions2.waypoints[index + 1]?.type;
color = directionsOptions2.waypoints[index + 1]?.color;
}
const a = {
route: leg.steps.map((step, i2) => ({
path: step.path,
trafficDuration: step.duration_in_traffic?.value || "normal"
})),
isHovered: false,
icon,
type: type || "Yok",
cords: {
lat: leg.start_location.lat(),
lng: leg.start_location.lng()
},
pathColor: color || directionsOptions2.waypoints[0]?.color
};
return a;
}
);
console.log("Directions Options -- 2:", directionsOptions2);
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(() => {
console.log("Routes ::", route);
}, [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_Key_" + index }, segment.route.map((s, i) => /* @__PURE__ */ React2.createElement("div", { key: "Route_variant_" + i }, s.route.map((r, j) => {
console.log(
"Stroke Weight:",
polylineOptions?.strokeColor !== null || void 0 ? polylineOptions?.strokeColor : s.pathColor
);
let opt = {
strokeColor: polylineOptions?.strokeColor !== void 0 ? polylineOptions?.strokeColor : s.pathColor,
strokeOpacity: polylineOptions?.strokeOpacity !== void 0 ? polylineOptions?.strokeOpacity : 0.5,
strokeWeight: polylineOptions?.strokeWeight !== void 0 ? polylineOptions?.strokeWeight : 2,
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) => {
}
}
));
}))))),
route && route.map((s, index) => {
let opt = 1;
return /* @__PURE__ */ React2.createElement("div", { key: "RoutePoint_" + index }, s?.markerPosition.end && /* @__PURE__ */ React2.createElement(
OverlayView2,
{
position: s?.markerPosition.end,
mapPaneName: OverlayView2.OVERLAY_MOUSE_TARGET,
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_finish_Overlay_end"
},
/* @__PURE__ */ React2.createElement(
CustomMarkers,
{
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_finish",
Icon: s?.markerPosition.end.icon.icon,
markerFill: s?.markerPosition.end.icon.fill,
markerTitle: s?.markerPosition.waypoints.length + 2,
onClick: () => markerOnClick(s)
}
)
), s?.markerPosition.waypoints.map(
(w, i, l) => {
console.log("Waypoints --Hakan:", w);
opt++;
return /* @__PURE__ */ React2.createElement(
OverlayView2,
{
position: w.location,
mapPaneName: OverlayView2.OVERLAY_MOUSE_TARGET,
key: "PlylineMarker_" + i + "_RoutePoint_Overlay"
},
/* @__PURE__ */ React2.createElement(
CustomMarkers,
{
key: "PlylineMarker_" + i + "_RoutePoint_",
Icon: w.icon?.icon,
markerFill: w.icon?.fill,
markerTitle: w.id + 1,
onClick: () => markerOnClick(w)
}
)
);
}
), s?.markerPosition.start && /* @__PURE__ */ React2.createElement(
OverlayView2,
{
position: s?.markerPosition.start,
mapPaneName: OverlayView2.OVERLAY_MOUSE_TARGET,
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_start_overlay"
},
/* @__PURE__ */ React2.createElement(
CustomMarkers,
{
key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_start",
Icon: s?.markerPosition.start.icon.icon,
markerFill: s?.markerPosition.start.icon.fill,
markerTitle: index + 1,
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
};