언어/java

카카오 지도 api / 쿼리문

깡 딱 2024. 1. 12. 22:36
728x90
<template>
    <section class="test">
      <div id="map"></div>
      <div id="result"></div>
    </section>
</template>
  
<script>
export default {
    name: "test",
    data() {
      return {
        map: null,
        markers: [],
        latitude: 0,
        longitude: 0
      };
    },
    
    created() {
      if (!("geolocation" in navigator)) {
        return;
      }
  
      // get position
      navigator.geolocation.getCurrentPosition(
        pos => { // 현재 위치를 찾기위해서 적는 위도 경도 
          this.latitude = pos.coords.latitude;
          this.longitude = pos.coords.longitude;
  
          if (window.kakao && window.kakao.maps) {
            this.initMap();
          } else {
            const script = document.createElement("script");
            script.onload = () => kakao.maps.load(this.initMap);
            script.src =
              "//dapi.kakao.com/v2/maps/sdk.js?autoload=false&appkey=키적으세요";
            document.head.appendChild(script);
          }
        },
        err => {
          alert(err.message);
        }
      );
    },


    methods: {
        
            initMap() {
        const container = document.getElementById("map");
        const options = {
            center: new kakao.maps.LatLng(33.450701, 126.570667),
            level: 5
        };
        this.map = new kakao.maps.Map(container, options);

        var imageSrc = 'https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/marker_red.png'; // 마커이미지의 주소입니다
        var imageSize = new kakao.maps.Size(64, 69); // 마커이미지의 크기입니다
        var imageOption = {offset: new kakao.maps.Point(27, 69)}; // 마커이미지의 옵션입니다.

        // 마커의 이미지정보를 가지고 있는 마커이미지를 생성합니다
        var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption);

        // 마커가 표시될 위치입니다
        var markerPosition = new kakao.maps.LatLng(this.latitude, this.longitude); 

        // 마커를 생성합니다
        var marker = new kakao.maps.Marker({
            position: markerPosition, 
            image: markerImage // 마커이미지 설정 
        });

        // 마커가 지도 위에 표시되도록 설정합니다
        marker.setMap(this.map); 

        this.displayMarker([[this.latitude, this.longitude]]);

        kakao.maps.event.addListener(this.map, 'click', (mouseEvent) => { // 이부분이 지도 위치를 클릭했을때 위도 경도가 뜨는 곳
            const latlng = mouseEvent.latLng;
            const message = '클릭한 위치의 위도는 ' + latlng.getLat() + ' 이고, 경도는 ' + latlng.getLng() + ' 입니다';
            const resultDiv = document.getElementById('result'); 
            resultDiv.innerHTML = message;
        });
    },
      displayMarker(markerPositions) {
        if (this.markers.length > 0) {
          this.markers.forEach(marker => marker.setMap(null));
        }
    
        const positions = markerPositions.map(
          position => new kakao.maps.LatLng(...position)
        );
    
        if (positions.length > 0) {
          this.markers = positions.map(
            position =>
              new kakao.maps.Marker({
                map: this.map,
                position
              })
          );
    
          const bounds = positions.reduce(
            (bounds, latlng) => bounds.extend(latlng),
            new kakao.maps.LatLngBounds()
          );
    
          this.map.setBounds(bounds);
        }
      }
    }
};
</script>
  
  
  
<style scoped>
.test {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
  
#map {
    width: 1000px;
    height: 2000px;
    border: 1px #a8a8a8 solid;
}
</style>

 

처음 짠 코드

이렇게 하면 내위치에 마커 두개가 표시되고 

클릭한 위치에 위도 경도가 뜬다. 근데 수정이 필요한거같다.

 

내가 하고싶은건 지도를 클릭했을때 위도 경도만 뜨게 만들고 싶기떄문에 

 

암튼 위 내용은 저장용도 이고 


밑에 내용이 버튼을 클릭했을때 위도 경도를 찾는 화면이다. 

<template>
  <section class="test">
      <div id="map"></div>
      <div id="result"></div>
      <button class="findLocationButton" v-on:click="toggleFindLocation">위도경도 찾기</button>
  </section>

  <div class="container">
        <div class="bottom-content">
                    <h2 class="main-title">장비 등록</h2>
                    <input type="text" placeholder="cctv 이름 적으세요"/>
                    <input type="text" placeholder="cctv 아이디를 입력하세요"
                    />
                    <input type="text" placeholder="cctv 위도 경도 입력"
                    />
                
                    <button @click="dataInsert()">등록</button>
                </div>
            </div>
</template>

<script>
export default {
  name: "test",
  data() {
      return {
          map: null,
          findLocation: false,
          clickListener: null
      };
  },
  
  created() {
      if (window.kakao && window.kakao.maps) {
          this.initMap();
      } else {
          const script = document.createElement("script");
          script.onload = () => kakao.maps.load(this.initMap);
          script.src =
              "//dapi.kakao.com/v2/maps/sdk.js?autoload=false&appkey=ced8d03ae8336e457549c7a6dc7e5e2a";
          document.head.appendChild(script);
      }
  },

  methods: {
      initMap() {
          const container = document.getElementById("map");
          const options = {
              center: new kakao.maps.LatLng(33.450701, 126.570667),
              level: 5
          };
          this.map = new kakao.maps.Map(container, options);
      },

      toggleFindLocation() {
        if (this.findLocation) {
            kakao.maps.event.removeListener(this.map, 'click', this.clickListener);
            this.findLocation = false;
        } else {
            this.clickListener = kakao.maps.event.addListener(this.map, 'click', (mouseEvent) => { 
                const latlng = mouseEvent.latLng;
                const resultDiv = document.getElementById('result'); 
                resultDiv.innerHTML = '클릭한 위치의 위도는 ' + latlng.getLat().toFixed(3) + ' 이고, 경도는 ' + latlng.getLng().toFixed(3) + ' 입니다';
                this.findLocation = false;
                kakao.maps.event.removeListener(this.map, 'click', this.clickListener);
            });
            this.findLocation = true;
        }
    }
  }
};
</script>

<style scoped>
.test {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
  
#map {
    width: 1000px;
    height: 2000px;
    border: 1px #a8a8a8 solid;
}

.findLocationButton {
    font-size: 16px;
    padding: 10px 20px;
    margin-top: 20px;
    border: none;
    border-radius: 5px;
    background-color: #ff6347;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.findLocationButton:hover {
    background-color: #ff4500;
}
</style>

 

 

버튼을 클릭하지 않으면 위도 경도가 안뜨지만

위도 경도 찾기를 눌렀을때는 위도와 경도 값이 나오게 만들었음

 

쿼리문을 짜보았는데 맞는지 모르겠다. 

위도 경도는 문자열로 저장 해야지 더 편할거같다는 생각이든다.

CREATE TABLE cctv_info
(
    eqpmn_id SERIAL PRIMARY KEY,
    eqpmn_lat numeric,
    eqpmn_lon numeric,
    camera_ip inet,
    eqpmn_nm VARCHAR(255),
    cntn_id VARCHAR(255),
    cntn_pw VARCHAR(255),
    reg_dt timestamp,
    rgtr_id VARCHAR(255),
    mdfcn_dt timestamp,
    mdfr_id VARCHAR(255),
    use_yn BOOLEAN,
    camera_nm VARCHAR(255)
) WITH (OIDS=FALSE);
728x90