Skip to content

Commit

Permalink
feat: add current location marker to Naver Map
Browse files Browse the repository at this point in the history
  • Loading branch information
keemsebin committed Nov 17, 2024
1 parent ab9a84d commit 5e64e77
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/components/features/NaverMap/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,24 @@ import { memo, useCallback, useEffect, useRef } from 'react';
import { useMarkers } from '@/hooks/common/useMarkers';
import { addMarkersToMap } from '@/utils/naver/addMarkersToMap';
import { clearExistingMarkers } from '@/utils/naver/clearExistingMarkers';
import { currentMarkersToMap } from '@/utils/naver/currentMakersToMap';
import { updateMarkerTitles } from '@/utils/naver/updateMarkerTitles';

import { Props } from './NaverMap.types';

// TODO : 대한민국 내에서만 표시 가능하도록 validation 추가
export const NaverMap = memo(
({ initialCenter = { lat: 37.549681, lng: 126.991911 }, initialZoom = 13 }: Props) => {
({
initialCenter = { lat: 37.549681, lng: 126.991911 },
initialZoom = 13,
isCurrent = false,
}: Props) => {
const mapRef = useRef<HTMLDivElement>(null);
const mapInstance = useRef<naver.maps.Map | null>(null);
const markersRef = useRef<naver.maps.Marker[]>([]);
const markerDataRef = useRef<Array<{ title: string; category: string }>>([]);
const currentLocationMarkerRef = useRef<naver.maps.Marker | null>(null);

const { markers } = useMarkers();

const handleZoomChange = useCallback((zoomLevel: number) => {
Expand All @@ -22,10 +29,14 @@ export const NaverMap = memo(

const clearMarkers = useCallback(() => {
clearExistingMarkers(markersRef, markerDataRef);
if (currentLocationMarkerRef.current) {
currentLocationMarkerRef.current.setMap(null);
currentLocationMarkerRef.current = null;
}
}, []);

useEffect(() => {
if (mapRef.current && window.naver) {
if (mapRef.current && window.naver && !mapInstance.current) {
const center = new window.naver.maps.LatLng(initialCenter.lat, initialCenter.lng);
const map = new window.naver.maps.Map(mapRef.current, {
center,
Expand All @@ -43,14 +54,17 @@ export const NaverMap = memo(
mapInstance.current = null;
};
}
}, [initialCenter.lat, initialCenter.lng, initialZoom, handleZoomChange]);
}, [initialZoom, handleZoomChange, initialCenter.lat, initialCenter.lng]);

useEffect(() => {
if (mapInstance.current && markers.length > 0) {
return addMarkersToMap(mapInstance, markers, markersRef, markerDataRef, clearMarkers);
}
if (mapInstance.current && isCurrent) {
return currentMarkersToMap(initialCenter, mapInstance.current, currentLocationMarkerRef);
}
clearMarkers();
}, [clearMarkers, markers]);
}, [clearMarkers, initialCenter, isCurrent, markers]);

return <div id="map" ref={mapRef} style={{ width: '100%', height: '100vh' }} />;
}
Expand Down

0 comments on commit 5e64e77

Please sign in to comment.