inflearn logo
강의

Course

Instructor

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

Mark data with markers.

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

338

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

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

제공되는 react_code.zip 중에 ..

0

1

1

커서 터미널에서 클로드코드 대화창에 이미지를 cmd+v 해도 붙여넣기가 안 됩니다.

0

6

1

스타터 킷 계획 모드 결과 (프로젝트생성2 강의)

0

5

0

깃 아이콘이 다른 문제

0

9

1

opus모델이 sonnet대비 사용량이 많다고하셨는데

0

13

1

우측 클로드 로고가 안떠요

0

23

1

[2회독] plan mode / task-manager / superpowers 등등

0

26

1

[2회독]Warp 사용문의

0

21

1

강의 내용 부분이 잘못 올려진 거 같아요!

0

20

0

이전 강의에서는 /init을 토큰사용량 이슈로 '보는것'만 제안 주셨는데요..

0

19

1

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

0

124

2

보일러플레이트 코드 오류

0

211

2

수업자료 오류

0

158

1

MongoDB Compass 관련 질문

0

348

1

카카오 맵 api

0

273

1

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

0

215

1

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

0

180

1

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

0

944

2

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

0

395

1

styled component 버튼 타입에러

0

505

1

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

0

530

1

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

1

489

1

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

0

404

1

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

1

496

1