'react navermap 현재위치'에 해당되는 글 1건

  1. 2022.03.17 react naver map 연동

react에서 naver지도를 연결 해줘야 하는 상황이 있어 찾아 보니 

 

https://github.com/zeakd/react-naver-maps

 

GitHub - zeakd/react-naver-maps: Controlled React Component for Naver Maps to handle zoom, center, etc.

Controlled React Component for Naver Maps to handle zoom, center, etc. - GitHub - zeakd/react-naver-maps: Controlled React Component for Naver Maps to handle zoom, center, etc.

github.com

https://zeakd.github.io/react-naver-maps/

 

React Naver Maps Style Guide

 

zeakd.github.io

이런 감사한 분이 있습니다. 가이드도 친절하고 react에 맞게 작업하기 편하게 만들어 주셨습니다.

간단한 사용방법 정리 했습니다.

 

모듈 설치를 해야 하니 해당 프로젝트 폴더에서

yarn add react-naver-maps 명령어를 실행 시킵니다.

그리고 사용할 페이지에서 2개의 패키지를 import합니다.

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

 

NaverMap -> 지도호출

Marker  -> 마커표시

RenderAfterNavermapsLoaded  -> 지도 비동기 호출을 위해

지도를 표현만 한다면 위의 3개만 있으면 됩니다. 자세한 내용은 가이드 사이트 보시면 잘 설명 되어 있습니다.

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

const NaverMapView =({mapLat, mapLng})=> {
    return (
        <>
            <RenderAfterNavermapsLoaded	   // render 후 지도 호출(비동기 랜더링)
                ncpClientId={'Client ID'} // 지도서비스 Client ID
                error={<p>error</p>}
                loading={<p>Maps Loading</p>}
                submodules={["geocoder"]} //추가로 사용할 서브모듈이 있는경우
            >
                <NaverMap
                    id="react-naver-maps"
                    style={{ width: '100%', height: '100vh' }}
                    center={{ lat: mapLat, lng: mapLng }}
                >
                    <Marker position={{ lat: mapLat, lng: mapLng }}/>
                </NaverMap>
            </RenderAfterNavermapsLoaded>
        </>
    )
}

export default NaverMapView;

해당 내용을 NaverMapView.js 로 생성하고 노출을 원하는 페이지에서 해당 페이지를 추가 해주시면 됩니다.

import NaverMapView from "../inc/NaverMapView";

const Map =()=>{ 
	let mapLat = "37.3595704";
	let mapLng = "127.105399";
    return(
        <div className="row mt-1" style={{height: "300px;"}}>
            <NaverApiMap mapLat={mapLat} mapLng={mapLng}></NaverApiMap>				
        </div>       
    );    
}
    
export default Map;

상황에 따라서 지도의 위치 및 마커를 변경 하고 싶은 경우 useState 를 사용해서 lat, lng를 정의 해줘야 합니다.

아래와 같이 선언 해주고

const [{ mapLat, mapLng }, setGeometricData] = useState({
  mapLat: 37.486708581137,
  mapLng: 127.037893303934,
});

해당 값을 상황에 맞게 변경 해주는 겁니다. 가장 사용 하지 않을거 같은 2가지 상황을 기준으로 작업 해본다면

(아래 2가지 경우 모두 https 에서만 허용되니 https에서 테스트 해주셔야 합니다.)

1. 내 위치 기준으로 지도,마커 변경

function getLocation() {
	if(navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(
			function (position){
				setGeometricData({mapLat:position.coords.latitude, mapLng:position.coords.longitude});
			}, 
			function (error){
				console.error(error);
			}, 
			{
				enableHighAccuracy: false,
				maximumAge: 0,
				timeout: Infinity
		});
	}else{
		alert('gps관련 정보가 없습니다.');
	}
}

함수를 이용 할 수 있습니다.

2. 주소 기준으로 지도,마커 이동

이 경우 geocoder 서브모듈을 사용해야 하는데 위의 네이버지도 호출 시 submodules={["geocoder"]} 라는 부분이 추가 되어 있는걸 확인 할 수 있습니다. 원하는 서브모듈이 있는경우 위와 같이 추가 해주시면 됩니다.(여러개의 경우 배열로 넣어 주시면 됩니다. 깃허브 이슈 내용에 보면 아래와 같이 기술 되어 있습니다.)

const mySubModule = ['panorama','geocoder'];

<RenderAfterNavermapsLoaded>
    ncpClientId={ClientID}
    submodules={mySubModules}

</RenderAfterNavermapsLoaded>

주소를 기준으로 좌표를 가지고 오는 함수를 아래와 같이 추가 해주고

const searchAddressToCoordinate =(address)=> {
	const navermaps = window.naver.maps;

	navermaps.Service.geocode(
		{
			query: address,
		},
		function (status, response) {
			if (status === navermaps.Service.Status.ERROR) {
				if (!address) {
					return alert('Geocode Error, Please check address');
				}
				return alert('Geocode Error, address:' + address);
			}

			if (response.v2.meta.totalCount === 0) {
				return alert('No result.');
			}

			let item = response.v2.addresses[0];
			console.log(item.x+" : "+item.y);
			setGeometricData({mapLat:item.x, mapLng:item.y});
		},
	);
}

호출 해주시면 됩니다. 가이드 문서에 이밖에 어떻게 하면 naver map을 react에서 편하게 사용 할 수 있는지

나와 있으니 참고 해보면 좋을거 같습니다.

반응형

'javascript > react' 카테고리의 다른 글

react 에서 fontawesome 사용하기  (0) 2022.03.17
react yarn 빌드하기  (0) 2022.03.15
react 에서 bootstrap 사용하기  (0) 2022.03.08
window react 개발 환경 설정  (0) 2021.06.21
Posted by 질주하는구
,