본문 바로가기
Angular.js

[Angular.js] kakao map에 원하는 위치 마커 표시하기

by 갈잃자 2024. 2. 20.

개요: 재난배상책임보험을 갱신해야 하는 시설물을 marker 표시하여 설계사나 ga회사들의 영업을 돕기 위한 프로젝트를 진행


1. index.ts에 scripts 추가

<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=발급받은 APP KEY를 넣으시면 됩니다."></script>

 

2. map 을 넣을 div 생성

<div #mapRef class="map"></div>

 

3. 지도 생성 및 원하는 x,y축 데이터를 받아와 마커 생성

export class FacilitiesLifeMapPageComponent extends SubscriptionBaseComponent implements OnInit {
  @ViewChild('mapRef', { static: true }) private mapRef: ElementRef; // html에서의 mapRef
  ngOnInit(): void {
    this.initializeMap();
  }

  constructor(
    private renewalFacilitiesService: NgRenewalFacilitiesService,
  ) {
    super();
  }
  
  // marker를 가지고 있는 array
  filteredFacilities = [];


  private initializeMap(): void {
    const options = {
      center: new kakao.maps.LatLng(33.450701, 126.570667), //기본 중앙 위치값
      level: 3 // 확대 축소 레벨
    };
    const map = new kakao.maps.Map(this.mapRef.nativeElement, options); //map 생성

    if (navigator.geolocation) { // 로케이션 설정 (현재 위치 허용한 경우)
      navigator.geolocation.getCurrentPosition((position) => {
        var lat = position.coords.latitude,
            lon = position.coords.longitude;

        var locPosition = new kakao.maps.LatLng(lat, lon);

        this.displayNowPosition(locPosition, map);
      });
    } else { //로케이션 설정 (현재 위치 거부한 경우, 기본값 설정)
      var locPosition = new kakao.maps.LatLng(33.450701, 126.570667);
      this.displayNowPosition(locPosition, map);
    }
    this.initFilteredFacilities(map)
  }

  private initMarkerMake(map,facility) { // y, x좌표를 경도 위도로 변환 후, map에 적용시키는 함수
    const markerPosition = new kakao.maps.LatLng(facility.epsg_y, facility.epsg_x);
    const marker = new kakao.maps.Marker({
      position: markerPosition
    })

    marker.setMap(map); // map에 marker 생성
  }

  private displayNowPosition(locPosition, map) { //접속위치를 중앙으로 위치시키는 함수
      // 지도 중심좌표를 접속위치로 변경합니다
      map.setCenter(locPosition);
  }

  private initFilteredFacilities(map) {
    // 임시 data
    const data = {
      apiSelect: '갱신가입대상시설물',
      region: { name: '서울특별시', value: '11' },
      period: '1주 이내',
      sector: undefined,
      page: 1
    }
    this.renewalFacilitiesService.getList(data).subscribe(
      res => {
       this.filteredFacilities = res;

       this.filteredFacilities.forEach((facility) => { //뽑아온 데이터를 반복문을 돌며, marker생성

        this.initMarkerMake(map, facility);
       })
      }
    )
  }
}

댓글