UNPKG

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.

464 lines (458 loc) 16.3 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { MapComponent: () => mapComponent_default, MapSelectLocation: () => MapSelectLocation }); module.exports = __toCommonJS(index_exports); // src/lib/mapComponent.tsx var import_api2 = require("@react-google-maps/api"); var import_react2 = __toESM(require("react"), 1); // src/lib/marker.tsx var import_react = __toESM(require("react"), 1); var import_api = require("@react-google-maps/api"); // src/lib/mapComponent.tsx var import_api3 = require("@react-google-maps/api"); var MapComponent = ({ RoutePoint, GoogleResult, markerOnClick, addNewRoutePoint, googleMapsApiKey, justDrawRoute, CustomMarkers, polylineOptions }) => { const [mapInstance, setMapInstance] = (0, import_react2.useState)(null); const [route, setRoute] = (0, import_react2.useState)([]); const [hoverState, setHoverState] = (0, import_react2.useState)({}); const [error, setError] = (0, import_react2.useState)(null); const [Points, setPoints] = (0, import_react2.useState)([]); const [ggRoute, setGGRoute] = (0, import_react2.useState)([]); (0, import_react2.useEffect)(() => { if (ggRoute.length === Points.length) { GoogleResult(ggRoute); } }, [ggRoute]); (0, import_react2.useEffect)(() => { setRoute([]); setPoints(RoutePoint); }, [RoutePoint]); (0, import_react2.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] ); } } ); }; (0, import_react2.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]); (0, import_react2.useEffect)(() => { console.log("Routes ::", route); }, [route]); const [activeMarker, setActiveMarker] = (0, import_react2.useState)(null); const handleMarkerClick = (id) => { setActiveMarker(id); }; const handleInfoWindowClose = () => { setActiveMarker(null); }; const handleMapOnLoad = (Instance) => { setMapInstance(Instance); }; const [mouseActivity, setMouseActivity] = (0, import_react2.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__ */ import_react2.default.createElement(import_api2.LoadScript, { googleMapsApiKey }, /* @__PURE__ */ import_react2.default.createElement( import_api2.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__ */ import_react2.default.createElement(import_api2.TrafficLayer, null), route && route.map((segment, index, all) => /* @__PURE__ */ import_react2.default.createElement("div", { key: "Route_Key_" + index }, segment.route.map((s, i) => /* @__PURE__ */ import_react2.default.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__ */ import_react2.default.createElement("div", { key: "Plyline_div_" + index + "_" + i + "_" + j }, /* @__PURE__ */ import_react2.default.createElement( import_api2.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__ */ import_react2.default.createElement("div", { key: "RoutePoint_" + index }, s?.markerPosition.end && /* @__PURE__ */ import_react2.default.createElement( import_api3.OverlayView, { position: s?.markerPosition.end, mapPaneName: import_api3.OverlayView.OVERLAY_MOUSE_TARGET, key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_finish_Overlay_end" }, /* @__PURE__ */ import_react2.default.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__ */ import_react2.default.createElement( import_api3.OverlayView, { position: w.location, mapPaneName: import_api3.OverlayView.OVERLAY_MOUSE_TARGET, key: "PlylineMarker_" + i + "_RoutePoint_Overlay" }, /* @__PURE__ */ import_react2.default.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__ */ import_react2.default.createElement( import_api3.OverlayView, { position: s?.markerPosition.start, mapPaneName: import_api3.OverlayView.OVERLAY_MOUSE_TARGET, key: "PlylineMarker_" + index + "_RoutePoint_" + index + "_start_overlay" }, /* @__PURE__ */ import_react2.default.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__ */ import_react2.default.createElement("div", null, error) )); }; var mapComponent_default = MapComponent; // src/lib/MapSelectLocation.tsx var import_api4 = require("@react-google-maps/api"); var import_react3 = __toESM(require("react"), 1); var import_react4 = require("react"); var MapSelectLocation = ({ address, onResult }) => { const mapRef = (0, import_react4.useRef)(null); const [mark, setMark] = (0, import_react4.useState)(); const containerStyle = { width: "100%", height: "400px", cursor: "crosshair !important" }; const center = { lat: 38.97271048516351, lng: 35.49849134823012 }; const [centerCoord, setCenterCoord] = (0, import_react4.useState)({ lat: 38.97271048516351, lng: 35.49849134823012 }); const [resultsCoords, setResultCoords] = (0, import_react4.useState)(); const [selectedAddress, setSelectedAddress] = (0, import_react4.useState)(null); (0, import_react4.useEffect)(() => { 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() }); } }); } }; (0, import_react4.useEffect)(() => { 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() }); } } }; (0, import_react4.useEffect)(() => { }, [mark]); return /* @__PURE__ */ import_react3.default.createElement("div", { className: "w-full h-full" }, /* @__PURE__ */ import_react3.default.createElement( import_api4.LoadScript, { googleMapsApiKey: process.env.NEXT_PUBLIC_REACT_APP_GOOGLE_MAPS_API_KEY }, /* @__PURE__ */ import_react3.default.createElement( import_api4.GoogleMap, { 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__ */ import_react3.default.createElement(import_api4.Marker, { position: mark }) ) )); };