Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

75 1 add google maps api with library #76

Merged
merged 2 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions apps/web/app/map/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use client';
import { Container } from '@tripie/design-system';
import Directions from 'components/Maps/Directions/Directions';

import GoogleMap from 'components/Maps/GoogleMap';
import Marker from 'components/Maps/Marker';
import { TRAVEL_MODE } from 'constants/maps';

const locations = [
{ lat: 35.62366, lng: 139.753634 },
{ lat: 35.6612723, lng: 139.7775608 },
{ lat: 35.6539099, lng: 139.7975056 },
{ lat: 35.662761, lng: 139.7991693 },
{ lat: 35.6660912, lng: 139.7876416 },
];

export default function Maps() {
Comment on lines +9 to +17
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

!! TODO

프롭스로 좌표받아오기

return (
<Container margin="none">
<GoogleMap>
{locations.map((position, index: number) => (
<div key={JSON.stringify(position)}>
<Marker position={position} onClick={() => alert(index + 1)} numberOfOrder={index + 1} />
{index < locations.length && (
<Directions
origin={locations[index]}
destination={locations[index + 1]}
travelMode={TRAVEL_MODE.DRIVING as google.maps.TravelMode}
/>
)}
</div>
))}
</GoogleMap>
</Container>
);
}
104 changes: 104 additions & 0 deletions apps/web/components/Maps/Directions/Directions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use client';

import { useMap, useMapsLibrary } from '@vis.gl/react-google-maps';
import { useEffect, useState } from 'react';

// import classNames from 'classnames/bind';
import { POLYGON_DOTTED } from 'constants/maps';
// import Style from './directions.module.scss';

type DirectionService = google.maps.DirectionsService;
type DirectionRenderer = google.maps.DirectionsRenderer;

interface DirectionsProps extends google.maps.DirectionsRequest {
selectedDirection?: string;
}

// const cx = classNames.bind(Style);

const Directions = ({
origin,
destination,
// selectedDirection,
travelMode = google.maps.TravelMode.DRIVING,
}: DirectionsProps) => {
const map = useMap();
const routesLibrary = useMapsLibrary('routes');
const [directionsService, setDirectionService] = useState<DirectionService | null>(null);
const [directionsRenderer, setDirectionRenderer] = useState<DirectionRenderer | null>(null);
const [routes, setRoutes] = useState<google.maps.DirectionsRoute[]>([]);
const [routeIndex, setRouteIndex] = useState(0);
const selected = routes[routeIndex];
const leg = selected?.legs[0];

useEffect(() => {
if (!map || !routesLibrary) {
return;
}
setDirectionService(new routesLibrary.DirectionsService());
setDirectionRenderer(new routesLibrary.DirectionsRenderer({ map }));
}, [routesLibrary, map]);

useEffect(() => {
if (!directionsService || !directionsRenderer) {
return;
}

directionsService
.route({
origin,
destination,
travelMode,
provideRouteAlternatives: true,
})
.then(res => {
directionsRenderer.setOptions({
hideRouteList: true,
draggable: true,
suppressMarkers: true,
polylineOptions: {
clickable: true,
strokeOpacity: 0,
icons: [POLYGON_DOTTED],
geodesic: true,
strokeColor: '#d43232',
},
});

directionsRenderer.setDirections(res);
setRoutes(res.routes);
return null;
});
}, [directionsService, directionsRenderer]);

useEffect(() => {
if (!directionsRenderer) {
return;
}
directionsRenderer.setRouteIndex(routeIndex);
}, [routeIndex, directionsRenderer]);

if (!leg) return null;

// !! 당장은 최소거리 선택할 필요 없음
// !!return (
// !! <div className={cx('directions', 'visible')}>
// !! {/* <div className={cx('directions', selectedDirection === JSON.stringify(location) ? 'visible' : null)}> */}
// !! <h2>{selected.summary}</h2>
// !! <p>{leg.start_address}</p>
// !! <p>distance: {leg.distance?.text}</p>
// !! <p>duration: {leg.duration?.text}</p>

// !! <h2>other routes</h2>
// !! <ul>
// !! {routes.map((route, index) => (
// !! <li key={route.summary}>
// !! <button onClick={() => setRouteIndex(index)}>{route.summary}</button>
// !! </li>
// !! ))}
// !! </ul>
// !! </div>
// !!);
};
Comment on lines +83 to +102
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

경로 선택할 수 있도록 하는 기능 꼭 필요하지 않을 수도?


export default Directions;
17 changes: 17 additions & 0 deletions apps/web/components/Maps/Directions/directions.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.directions {
position: absolute;
top: 0px;
right: 0px;
background-color: wheat;
& ul {
margin: 0px;
padding: 0px;
margin-right: 1rem;
}
& li {
list-style-type: none;
}
&:not(.visible) {
z-index: -2;
}
}
19 changes: 19 additions & 0 deletions apps/web/components/Maps/GoogleMap.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use client';
import { Map as ReactGoogleMaps } from '@vis.gl/react-google-maps';
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_CONTAINER_STYLE, DEFAULT_MAP_OPTIONS, DEFAULT_MAP_ZOOM } from 'constants/maps';
import { ReactNode } from 'react';

const GoogleMap = ({ children }: { children: ReactNode }) => {
return (
<ReactGoogleMaps
{...DEFAULT_MAP_OPTIONS}
style={DEFAULT_MAP_CONTAINER_STYLE}
defaultCenter={DEFAULT_MAP_CENTER}
defaultZoom={DEFAULT_MAP_ZOOM}
>
{children}
</ReactGoogleMaps>
);
};

export default GoogleMap;
43 changes: 43 additions & 0 deletions apps/web/components/Maps/Marker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use client';

import {
AdvancedMarkerProps,
InfoWindow,
AdvancedMarker as ReactGoogleMarker,
useAdvancedMarkerRef,
} from '@vis.gl/react-google-maps';
import Pin from './Pin';

interface MarkerProps extends AdvancedMarkerProps {
numberOfOrder?: number;
variation?: 'accommodation' | 'restaurant' | 'attraction';
}

interface InfowindowMarkerProps extends MarkerProps {
content?: string;
}

const Marker = ({ position, onClick, numberOfOrder, variation = 'attraction', ...props }: MarkerProps) => {
return (
<ReactGoogleMarker position={position} {...props} clickable={true} onClick={onClick}>
<Pin numberOfOrder={numberOfOrder} variation={variation} />
</ReactGoogleMarker>
);
};

const MarkerWithInfoWindow = ({ position, onClick, content = '마커 정보', ...props }: InfowindowMarkerProps) => {
const [markerRef, marker] = useAdvancedMarkerRef();

return (
<>
<ReactGoogleMarker {...props} position={position} ref={markerRef} clickable={true} onClick={onClick}>
<Pin />
</ReactGoogleMarker>
<InfoWindow anchor={marker}>{content}</InfoWindow>
</>
);
};

Marker.WithInfoWindow = MarkerWithInfoWindow;

export default Marker;
22 changes: 22 additions & 0 deletions apps/web/components/Maps/Pin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Pin as ReactGoogleMapsPin, PinProps as ReactGoogleMapsPinProps } from '@vis.gl/react-google-maps';
import { PIN_VARIATION } from 'constants/maps';

interface PinProps extends ReactGoogleMapsPinProps {
variation?: 'accommodation' | 'restaurant' | 'attraction';
numberOfOrder?: number;
}

const Pin = ({ numberOfOrder = 1, variation = 'accommodation', ...props }: PinProps) => {
return (
<ReactGoogleMapsPin
{...props}
background={PIN_VARIATION[variation]['background']}
borderColor={PIN_VARIATION[variation]['borderColor']}
glyphColor={PIN_VARIATION[variation]['glyphColor']}
>
{numberOfOrder}
</ReactGoogleMapsPin>
);
};
Comment on lines +9 to +20
Copy link
Collaborator Author

@Pyotato Pyotato Aug 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

마커의 디자인 커스텀
image


export default Pin;
75 changes: 75 additions & 0 deletions apps/web/constants/maps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const DEFAULT_MAP_CONTAINER_STYLE = {
width: '100%',
position: 'absolute',
left: '0px',
top: '0px',
right: '0px',
height: '100%',
};

const DEFAULT_MAP_CENTER = {
lat: -31.56391,
lng: 147.154312,
};
const DEFAULT_MAP_ZOOM = 18;

const DEFAULT_MAP_OPTIONS = {
zoomControl: true,
tilt: 0,
mapTypeId: 'roadmap',
mapId: 'DEMO_MAP_ID',
gestureHandling: 'greedy',
disableDefaultUI: true,
fullscreenControl: false,
colorScheme: 'FOLLOW_SYSTEM',
};

const API_KEY = process.env.NEXT_PUBLIC_GOOGLE_MAP_API as string;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 _ 👍

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로컬에서는 어떻게 하고계셔요 ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

엇..지금 pnpm run dev로 로컬로 돌리고 있는데..😅 혹시 제가 이해를 잘못한 걸까요..?


const PIN_VARIATION = {
accommodation: {
background: '#0f6e9d',
borderColor: '#003f64',
glyphColor: '#6096d9',
},
restaurant: {
background: '#9d220f',
borderColor: '#642100',
glyphColor: '#d98860',
},
attraction: {
background: '#4e0074',
borderColor: '#2f0064',
glyphColor: '#9660d9',
},
};
Comment on lines +29 to +45
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Marker의 pin 종류에 따른 스타일


const TRAVEL_MODE = {
BICYCLING: 'BICYCLING',
DRIVING: 'DRIVING',
TRANSIT: 'TRANSIT',
WALKING: 'WALKING',
};

const LINE_SYMBOL = {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4,
};

const POLYGON_DOTTED = {
icon: LINE_SYMBOL,
offset: '0',
repeat: '20px',
};

export {
API_KEY,
DEFAULT_MAP_CENTER,
DEFAULT_MAP_CONTAINER_STYLE,
DEFAULT_MAP_OPTIONS,
DEFAULT_MAP_ZOOM,
PIN_VARIATION,
POLYGON_DOTTED,
TRAVEL_MODE,
};
12 changes: 9 additions & 3 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@
"clean": "rm -rf ./node_modules && rm -rf ./.turbo && rm -rf ./dist && rm -rf ./.next"
},
"dependencies": {
"@googlemaps/markerclusterer": "^2.5.3",
"@react-google-maps/api": "^2.19.3",
"@tripie/design-system": "workspace:*",
"@tripie/hooks": "workspace:*",
"@vis.gl/react-google-maps": "^1.1.0",
"classnames": "^2.5.1",
"google": "^2.1.0",
"google-maps-react-markers": "^2.0.11",
"next": "^14",
"react": "^18.3",
"react-dom": "^18.3"
Expand All @@ -26,13 +31,14 @@
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@tripie/jest": "workspace:*",
"@types/google.maps": "^3.55.12",
"@types/jest": "^29.5.12",
"@types/node": "^20",
"@types/react": "^18.3.3",
"babel-jest": "^29.7.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"msw": "^2.2.10",
"ts-jest": "^29.2.4",
"babel-jest": "^29.7.0",
"identity-obj-proxy": "^3.0.0"
"ts-jest": "^29.2.4"
}
}
9 changes: 9 additions & 0 deletions apps/web/provider/MapProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
'use client';

import { APIProvider } from '@vis.gl/react-google-maps';
import { API_KEY } from 'constants/maps';
import { ReactNode } from 'react';

export function MapProvider({ children }: { children: ReactNode }) {
return <APIProvider apiKey={API_KEY}>{children}</APIProvider>;
}
7 changes: 6 additions & 1 deletion apps/web/provider/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ReactNode } from 'react';

import dynamic from 'next/dynamic';
import { MapProvider } from './MapProvider';

/**
* https://nextjs.org/docs/pages/building-your-application/optimizing/lazy-loading#with-no-ssr
Expand All @@ -12,5 +13,9 @@ export default function Provider({
}: Readonly<{
children: ReactNode;
}>) {
return <ThemeProvider>{children}</ThemeProvider>;
return (
<ThemeProvider>
<MapProvider>{children}</MapProvider>
</ThemeProvider>
);
}
Loading
Loading