Recent Posts
Recent Comments
Archives
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 모던 자바스크립트
- 티스토리챌린지
- 자주 까먹는
- deep dive
- 스파르타코딩클럽
- 오블완
- array정적메서드
- 초기셋팅
- 모던자바스크립트
- js
- 내일배움캠프
- 코테
- 구글 로그인
- 프로그래머스
- nextjs
- git
- error
- domain
- 코드카타
- useRouter
- 프로젝트 셋팅
- vercel
- vscode
- 코딩테스트
- 최적화
- CORS
- React
- 셋팅
- 소셜 로그인
- Next
- Today
- Total
도록
[google map] react에서 구글 맵 연동하기 / 2탄. 경로 그리기 본문
참고 문서) 경로 그리기
- https://console.cloud.google.com/google/maps-apis/discover/text-directions?project=genuine-sector-430902-r9
- https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/reference/library-interfaces?hl=ko#RoutesLibrary
1탄에서 사용한 lib에는 경로 그리는 방법이 존재 하지 않는다.
기본적으로 google api 가져다 쓰는 방법이니까 lib를 뜯어서 수정하면 가능은 하겠지만...
구글 맵을 그렇게까지 만지고 싶지는 않아서 다른 라이브러리 사용하는 방식으로 해결함
import { LatLng } from "@/types/LatLng";
import {
GoogleMap,
LoadScript,
Marker,
Polyline,
} from "@react-google-maps/api";
import React, { useState } from "react";
const KEY: string = process.env.NEXT_PUBLIC_MAP_API_KEY!;
type props = { locations: LatLng[] };
function Map({ locations }: props) {
const [isInit, setIsInit] = useState<boolean>(false);
const center: LatLng = getCenter(locations);
const handleOnLoad = () => setIsInit(true);
const markerProps = isInit
? {
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: "#e08181",
fillOpacity: 1,
scale: 10,
strokeColor: "black",
strokeWeight: 2,
},
}
: {};
return (
<LoadScript googleMapsApiKey={KEY} onLoad={handleOnLoad}>
<GoogleMap
mapContainerStyle={{
width: "100%",
height: "100vh",
}}
center={center}
zoom={7}
>
{locations.map((location, i) => (
<Marker key={i} position={location} label={i + ""} {...markerProps} />
))}
<Polyline
path={locations}
options={{
strokeColor: "#535353",
strokeOpacity: 0.8,
strokeWeight: 2,
}}
/>
</GoogleMap>
</LoadScript>
);
}
export default React.memo(Map);
function getCenter(locations: LatLng[]): LatLng {
let lat = 0,
lng = 0;
const length = locations.length;
for (let i = 0; i < length; i++) {
const item = locations[i];
lat += item.lat;
lng += item.lng;
}
return { lat: lat / length, lng: lng / length };
}
export type LatLng = { lat: number, lng: number };
'Today I Learned' 카테고리의 다른 글
말줄임표 css (0) | 2024.08.01 |
---|---|
모의 면접, 피드백 정리 (0) | 2024.08.01 |
punycode deprecated 에러 (0) | 2024.07.29 |
[google map] react에서 구글 맵 연동하기 / 1탄. 마커 찍기 (0) | 2024.07.29 |
[next] 파라미터 가져오는 방법 (0) | 2024.07.09 |