Light Blue Pointer
본문 바로가기
Developing/TIL(Develop)

네이버 지도 API에 좌표로 마커 표시하기

by Greedy 2024. 3. 25.

1. head에 네이버 지도를 달아준다

<script
      src="https://oapi.map.naver.com/openapi/v3/maps.js?ncpClientId={본인의 클라이언트 아이디}&submodules=geocoder"
      type="text/javascript"></script>

2. 지도를 넣고싶은 자리에 코드를 넣어준다

      <div id="map" padding="10px" style="width:1000px; height:450px;"></div>

3. 자바스크립트 코드로 지도와 마커를 출력함

<script>
    function drawMap(lat, lng) {
    var map = new naver.maps.Map('map', {
      center: new naver.maps.LatLng(lat, lng),
      zoom: 15
    });

    var marker = new naver.maps.Marker({
      position: new naver.maps.LatLng(lat, lng),
      map: map
    });
  }
  
  </script>

 

데이터를 ajax로 받아와서 넣어줬다

function getData() {

    $.ajax({
      type: 'GET',
      url: `/api/v1/posts/[[${postId}]]`,
      dataType: "json",
      contentType: 'application/json',
      data: {},
      success: function (response) {
        latitude = response.data.latitude;
        longitude = response.data.longitude
        
       drawMap(latitude, longitude);
      },
      error: function (error) {
        console.error('Error:', error);
      }
    });
  }