[기업협업]Day3. React로 Naver Map에 Marker 표시하기(customizing)

Joah·2022년 7월 20일
1

기업협업

목록 보기
3/15
post-thumbnail

npm install react-naver-maps

Naver Map은 React를 위해 따로 API를 만든 것이 아니기 때문에 라이브러리를 설치해야 한다.

설치 이후 다양한 컴포넌트를 사용할 수 있다.

모듈을 살펴보면,,,

어떤 컴포넌트들을 사용할 수 있는지 볼 수 있다.
아직도 의문이지만 Overlay 컴포넌트를 사용할 수 없다...왜 안되는지..


⛳ Marker 표시하기

지난 게시글에서 GeoJSON으로 좌표 데이터를 구현하는 방법을 알아보았다.
지난 게시글
이제 지도에 Marker를 표시할 수 있다.

  1. react-naver-maps에서 기본적으로 제공하는 <Marker/> 컴포넌트를 import

  2. 네이버 맵 공식문서에서 제공하는 다양한 속성을 파악한다.

import React, { useEffect, useState } from 'react';
import './Map.scss';

import {
  RenderAfterNavermapsLoaded,
  NaverMap,
  Marker,
} from 'react-naver-maps';

function NaverMapAPI() {
  const navermaps = window.naver.maps;

  const [mydata, setMyData] = useState([]);

  useEffect(() => {
    fetch('/data/lineTwo.json')
      .then(res => res.json())
      .then(data => {
        setMyData(data.line);
      });
  }, []);

  if (mydata.length === 0) return;

  return (
    <NaverMap
      id="react-naver-maps-introduction"
      style={{ width: '100%', height: '90vh', borderTop: 'transparent' }}
      defaultCenter={{ lat: 37.497175, lng: 127.027926 }}
      defaultZoom={14}
    >
      {mydata.map(input => (
        <Marker
          key={input.station}
          position={new navermaps.LatLng(...input.code)}
          animation={2}
		  title={input.station}
          icon={{
            content: 
                `<button class="markerBox">
                <div class="totalOrder">${input.order}</div>
                ${input.station}</button>`,
          	}}
        />
      ))}
    </NaverMap>
  );
}

const Map = () => {
  return (
    <RenderAfterNavermapsLoaded
      ncpClientId="발급받은 client key"
      error={<p>Maps Load Error</p>}
      loading={<p>Maps Loading...</p>}
    >
      <NaverMapAPI />
    </RenderAfterNavermapsLoaded>
  );
};

export default Map;
  • position : Marker가 표시될 좌표

  • icon : Marker의 아이콘 커스터마이징(스타일은 scss로 진행)

  • title : Marker가 가지고 있는 기본적인 Marker 이름

  • animation : Marker가 나타날 때 보여지는 애니메이션(1,2,3)

new navermaps.LatLng(...input.code) 좌표를 그려주는 메서드

네이버 지도에서 기본적으로 제공하는 좌표를 화면에 나타내는 메서드는 위와 같다. new navermaps.LatLng([x축 좌표, y축 좌표])의 기본값에서 Mockdata의 데이터를 map 함수를 통해 구현했다.

Mockdata

MockData는 공공 API에서 제공하는 서울역 지하철 2호선의 일부를 가져와서 작성했다.

{
  "line": [
    { "order": 11, "station": "잠실새내", "code": [37.511687, 127.086162] },
    { "order": 23, "station": "종합운동장", "code": [37.510997, 127.073642] },
    { "order": 1456, "station": "삼성", "code": [37.508844, 127.06316] },
    { "order": 71, "station": "선릉", "code": [37.504503, 127.049008] },
    { "order": 1341, "station": "역삼", "code": [37.500622, 127.036456] },
    { "order": 65, "station": "강남", "code": [37.497175, 127.027926] },
    { "order": 333, "station": "교대", "code": [37.493415, 127.01408] },
    { "order": 575, "station": "방배", "code": [37.481426, 126.997596] },
    { "order": 3, "station": "사당", "code": [37.47653, 126.981685] },
    { "order": 578, "station": "신대방", "code": [37.487462, 126.913149] },
    {
      "order": 976,
      "station": "구로디지털단지",
      "code": [37.485266, 126.901401]
    },
    { "order": 1343, "station": "신도림", "code": [37.508725, 126.891295] },
    { "order": 2345, "station": "문래", "code": [37.517933, 126.89476] }
  ]
}

SCSS

@import '/src/styles/variables.scss';

.markerBox {
  padding-left: 25px;
  position: relative;
  width: 85px;
  height: 30px;
  font-size: 5px;
  background-color: yellow;
  border-radius: 35px;

  .totalOrder {
    text-align: center;
    line-height: 30px;
    width: 25px;
    height: 100%;
    top: 0;
    left: 0;
    background-color: blue;
    color: white;
    border-radius: 50%;
    position: absolute;
  }
}

결과물


⛳ Long Story Short

블로그에 작성하니 금방? 쉽게 구현한 것 처럼 보이지만 사실 공식문서에 없는 부분을 하나하나 찾아서 작성하는 과정에서 하루의 시간이 걸렸다. 하지만 그렇게 배워야 결코 잊어버리지 않는 법
새로고침을 클릭하고 마커들이 두둥...!하면서 떨어지는 모습을 보니 아주 뿌듯했다.

profile
Front-end Developer

0개의 댓글