하루 기록

[google map] react에서 구글 맵 연동하기 / 2탄. 경로 그리기 본문

Today I Learned

[google map] react에서 구글 맵 연동하기 / 2탄. 경로 그리기

떼굴펜 2024. 7. 30. 14:37

참고 문서) 경로 그리기 


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 };