기본 통합 절차
바이두 지도 API를 HTML 페이지에 추가하는 기본 방식은 다음과 같습니다:
<script src="https://api.map.baidu.com/api?type=webgl&v=1.0&ak=YOUR_API_KEY"></script>
<script>
const map = new BMapGL.Map('container');
map.centerAndZoom(new BMapGL.Point(116.404, 39.928), 15);
map.addEventListener('click', (event) => {
console.log(`선택 좌표: ${event.latlng.lng},${event.latlng.lat}`);
});
</script>
프레임워크 통합 주의사항
Vue.js 같은 SPA 프레임워크 사용 시 주의할 점:
- 공식 예제의 document.write()는 페이지 전체를 재작성하므로 Vue 컴포넌트에서 사용 불가
- 대신 동적 스크립트 로딩 방식으로 리소스 관리 필요
- 모바일 환경에서는 CSS 스타일 오류 발생 가능성 높음
Vue2 컴포넌트 구현
지도 표시, 위치 선택, 주소 검색 기능을 포함한 컴포넌트 예제:
<template>
<div class="map-wrapper">
<div :id="mapElementId" class="map-area"></div>
<div class="search-box">
<input :id="searchInputId" placeholder="주소 검색"/>
</div>
</div>
</template>
<script>
export default {
props: {
configHandler: { type: Function, default: () => {} }
},
data: () => ({
mapInstance: null,
mapElementId: `map-${Date.now()}`
}),
computed: {
searchInputId() { return `${this.mapElementId}-search` }
},
methods: {
async loadMapResources() {
if (window._BaiduMapLoaded) return;
const loadAsset = (url, type) => new Promise(resolve => {
const element = type === 'script'
? document.createElement('script')
: document.createElement('link');
if (type === 'script') {
element.src = url;
} else {
element.rel = 'stylesheet';
element.href = url;
}
element.onload = resolve;
document.head.appendChild(element);
});
window.BMAP_PROTOCOL = "https";
await Promise.all([
loadAsset(`https://api.map.baidu.com/getscript?type=webgl&ak=YOUR_API_KEY`, 'script'),
loadAsset('https://api.map.baidu.com/res/webgl/10/bmap.css', 'style')
]);
window._BaiduMapLoaded = true;
},
initMapFeatures() {
this.setupClickHandler();
this.addLocationControl();
this.enableSearch();
},
setupClickHandler() {
this.mapInstance.addEventListener('click', event => {
this.placeMarker(event.latlng);
});
},
placeMarker(position) {
this.mapInstance.clearOverlays();
const point = new BMapGL.Point(position.lng, position.lat);
new BMapGL.Marker(point, { draggable: true });
this.mapInstance.centerAndZoom(point, 15);
this.resolveCoordinates(point);
}
},
async mounted() {
await this.loadMapResources();
this.mapInstance = new BMapGL.Map(this.mapElementId);
this.mapInstance.centerAndZoom(new BMapGL.Point(116.404, 39.928), 15);
this.configHandler(this.mapInstance);
this.initMapFeatures();
}
};
</script>
<style scoped>
.map-wrapper, .map-area {
width: 100%;
height: 80vh;
}
.search-box {
position: absolute;
top: 10px;
z-index: 100;
}
</style>
모바일 환경 대응
모바일에서 지도 미표시 문제 해결 방법:
- 컨테이너 요소에 명시적 width/height 설정 필수
- CSS에서 viewport 단위(vh/vw) 사용 권장
- z-index 충돌 방지를 위한 레이어 관리