inflearn logo
강의

Course

Instructor

Creating a map service with React + Express (TypeScript) by the developer of Corona Map

Mark data with markers.

지도가 두개가 열리는 것 같습니다

359

WinterFlw

1 asked

0

보시면 하나의 지도 div에 두개가 열리는 것 같습니다.

실제로 지도가 두개가 열려 서로 level이 달라 겹치는 모습입니다. 뒷장의 지도에는 마커가 표기되지 않습니다.

아래는 맵과 관련된 코드들입니다.

mern_client/src/components/common/Map/index.tsx

import React, { useEffect } from 'react';


interface MapProps {
    width: string;
    height: string;
    initMap?: (map: naver.maps.Map) => void;
}

function Map({width, height, initMap}: MapProps) {

    useEffect(() => {
        const mapOptions = {
            center: new naver.maps.LatLng(37.3595704, 127.105399),
            zoom: 10
        };
        
        const map = new naver.maps.Map('map', mapOptions);
        if (initMap){
            initMap(map);
        }
    }, []); 

    return <div id="map" style={{width, height}}></div>;
}

export default Map;

mern_client/src/components/MapContainer.tsx

import { useSetAtom } from "jotai";
import React from 'react';
import Map from './common/Map';
import { mapAtom } from "../atoms/map";

function MapContainer() {
    const setMap = useSetAtom(mapAtom);

    const initMap = (map: naver.maps.Map) => {
        setMap(map);
        naver.maps.Event.addListener(map, 'click', () => {
            console.log("맵 클릭");
        });
    };
    return <Map width="100%" height='100%' initMap={initMap}/>
};

export default MapContainer;

mern_client/src/atoms/map.ts

import { atom } from 'jotai';

export const mapAtom = atom<naver.maps.Map | null>(null);

react node.js mongodb express typescript

Answer 1

-1

communityai8509

안녕하세요 WinterFlw님, 인프런 AI 인턴이에요.

화면을 보면 하나의 div에 두 개의 지도가 겹쳐서 열린 것으로 보입니다. 이런 경우에는 초기화할 때 id가 “map”인 div 태그를 찾아서 해당 div에 지도를 생성하는 방법을 사용합니다.

현재 코드를 살펴보면, Map 컴포넌트에서 id가 “map”인 div에 지도를 생성하고 있습니다. 하지만 MapContainer 컴포넌트에서도 Map 컴포넌트를 사용하여 또 다른 지도를 생성하고 있습니다.

해결 방법으로는 다음과 같이 수정할 수 있습니다.

  1. Map 컴포넌트의 id를 props로 받아오도록 수정합니다.
  2. MapContainer 컴포넌트에서 두 번째 Map 컴포넌트를 삭제하고, 첫 번째 Map 컴포넌트에 id를 props로 전달합니다.

수정된 코드는 아래와 같습니다.

mern_client/src/components/common/Map/index.tsx

import React, { useEffect } from 'react';

interface MapProps {
    id: string;
    width: string;
    height: string;
    initMap?: (map: naver.maps.Map) => void;
}

function Map({id, width, height, initMap}: MapProps) {

    useEffect(() => {
        const mapOptions = {
            center: new naver.maps.LatLng(37.3595704, 127.105399),
            zoom: 10
        };

        const map = new naver.maps.Map(id, mapOptions);
        if (initMap){
            initMap(map);
        }
    }, []);

    return <div id={id} style={{width, height}}></div>;
}

export default Map;

mern_client/src/components/MapContainer.tsx

import { useSetAtom } from "jotai";
import React from 'react';
import Map from './common/Map';
import { mapAtom } from "../atoms/map";

function MapContainer() {
    const setMap = useSetAtom(mapAtom);

    const initMap = (map: naver.maps.Map) => {
        setMap(map);
        naver.maps.Event.addListener(map, 'click', () => {
            console.log("맵 클릭");
        });
    };
    return <Map id="map" width="100%" height='100%' initMap={initMap}/>
};

export default MapContainer;

이렇게 수정하면 div 태그의 id가 “map”인 부분에 하나의 지도만 생성되고 겹치는 문제가 해결될 것입니다. 감사합니다!

0

WinterFlw

수정해도

Compiled with warnings.

[1]

[1] [eslint]

[1] src/components/common/Map/index.tsx

[1] Line 22:8: React Hook useEffect has missing dependencies: 'id' and 'initMap'. Either include them or remove the dependency array. If 'initMap' changes too often, find the parent component that defines it and wrap that definition in useCallback react-hooks/exhaustive-deps

[1]

[1] Search for the keywords to learn more about each warning.

[1] To ignore, add // eslint-disable-next-line to the line before.

[1]

[1] WARNING in [eslint]

[1] src/components/common/Map/index.tsx

[1] Line 22:8: React Hook useEffect has missing dependencies: 'id' and 'initMap'. Either include them or remove the dependency array. If 'initMap' changes too often, find the parent component that defines it and wrap that definition in useCallback react-hooks/exhaustive-deps

[1]

[1] webpack compiled with 1 warning

이러한 오류를 내고, 맵은 그대로 두개가 나옵니다.

31강 학습자료에 프롬프트가 엉뚱한것이 있어요

0

5

0

plan mode를 진행하는것에 있어서

0

5

1

오픈톡 인원이 다 차서 들어가지를 못 하네요...

0

11

1

클로드 코드 설치 관련

0

11

1

스타터킷 중요도에 대한 질문입니다.

0

14

1

mission12-01 guide.md파일 누락

0

14

1

슬라이드 오타

0

19

0

강의 소스 코드는 어디서 볼수 있나여?

1

29

1

전체적인 개발에 대해 문의드립니다.

1

37

1

챌린지 시작일 문의

0

39

0

수업자료 다운로드 시 빈폴더만 나오네요

0

152

2

보일러플레이트 코드 오류

0

245

2

수업자료 오류

0

187

1

MongoDB Compass 관련 질문

0

382

1

카카오 맵 api

0

301

1

mongodb 및 mongoose 초기 세팅에서 다운로드 질문입니다

0

237

1

보일러 플레이트 다운 시 빈 폴더

0

201

1

Node.js 버전 차이로 인한 오류 발생(추정)

0

965

2

[참고] 서버 보일러 플레이트에 axios 없네요~

0

416

1

styled component 버튼 타입에러

0

522

1

초기 보일러플레이트 설정문제

0

548

1

serach.ts 파일 질문드립니다.

1

505

1

강의자료 소스코드 질문드립니다.

0

424

1

맵 클릭 이벤트 추가 강의와 Jotai 강의 순서에 대해 건의드립니다.

1

512

1