MarkerClustering 초기화 (feat. 네이버지도+리액트)

ILOV-IT·2025년 1월 23일

1. MarkerClustering.js 다운로드 및 저장

네이버 공식 Github에서 MarkerClustering.js 파일을 다운로드하고, 리액트의 public 디렉토리에 넣는다.

네이버 공식 Github: https://github.com/navermaps/marker-tools.js/tree/master/marker-clustering/src

2. MarkerClustering.js 파일 수정

MarkerClustering.js 파일을 열고 상단에 글로벌로 설정하는 코드를 넣는다.

/**
 * Copyright 2016 NAVER Corp.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

(function (global) {
	if (!global.naver || !global.naver.maps) {
	  setTimeout(() => {
		global.naver.maps = global.naver.maps || {};
		global.naver.maps.MarkerClustering = MarkerClustering;
	  }, 3000);
	} else {
	  global.naver.maps.MarkerClustering = MarkerClustering;
	}
  })(window);

3. index.html에 MarkerClustering.js 추가

네이버지도 API 로드 후, /MarkerClustering.js를 로드하도록 수정한다. vite는 기본적으로 public에 접근가능하지만, 접근이 안 되는 경우 vite config를 수정한다.

<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=___YOUR_TOKEN___"></script>
<script type="text/javascript" src="/MarkerClustering.js"></script>

4. 리액트에서 스크립트 로드

  useEffect(() => {
    const loadScript = (url: string, callback: () => void) => {
      const script = document.createElement('script');
      script.src = url;
      script.onload = callback;
      document.body.appendChild(script);
    };
  
    loadScript('/MarkerClustering.js', () => {
      if (!window.naver?.maps?.MarkerClustering) {
        console.error('MarkerClustering is still not available');
      } else {
        console.log('MarkerClustering successfully registered');
      }
    });
  }, []);
profile
because we know you'll love it

0개의 댓글