구글 지도를 이용하여 서버에서 보내 준 주소로 지도를 표시하고 마커를 생성 해보려고 합니다.
저는 VUE2.7 버전을 사용 중 입니다.
먼저, Goole Maps Platform에 가서 자신의 API 키를 발급 받는다.
아래 구글 클라우드 콘솔(Google Cloud Console) 링크로 들어가면 API 키를 발급받을 수 있습니다.
한 달에 28,500번 정도는 무료로 호출이 가능합니다.
https://developers.google.com/maps/gmp-get-started?hl=ko
그 다음 맵 API가 생성될 컴포넌트를 만들어 줍니다.
<template>
<div>
<h5
class="mb-2 color_red"
v-if="bookingResult && bookingResult.status === 'fail'"
>
Invalid reservation number. Please check again.
</h5>
<div style="height: 600px" id="map"></div>
</div>
</template>
<script src="https://maps.googleapis.com/maps/api/js?key=발급받은 API_KEY"></script>
<script>
export default {
props: ["bookingResult"],
data() {
return {
map: null,
mapCenter: { lat: 33.5048, lng: 126.4984 },
companyGps: this.getInitialCompanyGps(),
markers: [], // 마커를 저장할 배열을 추가합니다.
};
},
mounted() {
this.initMap();
},
methods: {
getInitialCompanyGps() {
return Array.isArray(this.bookingResult) &&
this.bookingResult.length > 0 &&
this.bookingResult[0].companyGps
? {
lat: parseFloat(this.bookingResult[0].companyGps.lat),
lng: parseFloat(this.bookingResult[0].companyGps.lng),
}
: this.mapCenter;
},
initMap() {
const centerLocation = this.companyGps ? this.companyGps : this.mapCenter;
this.map = new google.maps.Map(document.getElementById("map"), {
center: centerLocation,
zoom: 19,
maxZoom: 20,
minZoom: 3,
streetViewControl: true,
mapTypeControl: true,
fullscreenControl: true,
zoomControl: true,
});
if (
this.bookingResult &&
Array.isArray(this.bookingResult) &&
this.bookingResult.length > 0 &&
this.bookingResult[0].vhlNum
) {
this.setMarker(centerLocation, this.bookingResult[0].vhlNum);
}
},
setMarker(Points, Label) {
// 기존 마커를 지우는 로직
this.clearMarkers();
// 새 마커 생성
const marker = new google.maps.Marker({
position: Points,
map: this.map,
label: {
text: Label,
color: "black",
fontSize: "20px",
},
});
// 생성한 마커를 배열에 저장합니다.
this.markers.push(marker);
},
clearMarkers() {
// 배열에 저장된 모든 마커를 지도에서 제거합니다.
for (let marker of this.markers) {
marker.setMap(null);
}
// 마커 배열을 비웁니다.
this.markers = [];
},
},
watch: {
bookingResult: {
deep: true,
handler(newVal) {
if (
Array.isArray(newVal) &&
newVal.length > 0 &&
newVal[0].companyGps
) {
this.companyGps = {
lat: parseFloat(newVal[0].companyGps.lat),
lng: parseFloat(newVal[0].companyGps.lng),
};
this.map.setCenter(this.companyGps);
this.setMarker(this.companyGps, newVal[0].vhlNum);
}
},
},
},
};
</script>
처음에 mounted되면 initMap을 실행시켜 new google.maps.Map 생성자로 지도 객체를 생성해주는데
첫번째 인자로는 지도가 생성될 요소
두번째 인자로는 지도에 적용될 옵션 객체가 들어갑니다
center는 지도 위에 보여줄 중심 위치 입니다.
zoom은 지도 확대 정도 입니다.
밑에 Control은 말 그대로 조절 할건지 말건지의 여부 입니다.
setMarker는 지도 위에 표시되는 마커입니다.
그리고 lat과 lng은 무조건 Number 타입으로 들어가야 합니다.