一、在index.html文件中引入天地图JavaScript API:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 2 TMap Demo</title>
<script src="http://api.tianditu.gov.cn/api?v=2.0&tk=你的key"></script>
</head>
<body>
<div id="app"></div>
<script src="/dist/build.js"></script>
</body>
</html>
二、创建Vue组件,例如TMapMarker.vue
<template>
<div class="tmap-search-marker">
<input type="text" v-model="keyword" placeholder="请输入关键字" />
<button @click="search">搜索</button>
<div ref="mapContainer" class="map-container"></div>
<div v-if="marker">
<p>经度:{{ marker.lng }}</p>
<p>纬度:{{ marker.lat }}</p>
<p>地址:{{ marker.address }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
map: null,
marker: null
};
},
mounted() {
this.loadMap();
this.map.addEventListener("click", (e) => {
this.handleMapClick(e.lnglat);
});
},
methods: {
loadMap() {
this.map = new T.Map(this.$refs.mapContainer, {
projection: "EPSG:4326"
});
this.map.centerAndZoom(new T.LngLat(116.397428, 39.90923), 13);
},
search() {
if (!this.keyword) return;
const searchService = new T.MapService();
searchService.queryByKeyword(this.keyword, (e) => {
if (e.getStatus() === 0) {
const result = e.getResult();
if (this.marker) {
this.map.removeOverLay(this.marker);
}
const poi = result.getPoiList().getPoi(0);
const marker = new T.Marker(new T.LngLat(poi.getLng(), poi.getLat()));
this.map.addOverLay(marker);
this.marker = {
lng: poi.getLng(),
lat: poi.getLat(),
address: poi.getAddress()
};
}
});
},
handleMapClick(lnglat) {
if (this.marker) {
this.map.removeOverLay(this.marker);
}
const marker = new T.Marker(lnglat);
this.map.addOverLay(marker);
this.marker = {
lng: lnglat.getLng(),
lat: lnglat.getLat(),
address: ""
};
const geocoder = new T.Geocoder();
geocoder.getLocation(lnglat, (result) => {
if (result.getStatus() === 0) {
this.marker.address = result.getAddress();
}
});
}
}
};
</script>
<style scoped>
.map-container {
width: 100%;
height: 400px;
}
</style>
三、vue文件中使用
<template>
<div>
<TMapMarker />
</div>
</template>
<script>
import TMapMarker from './TMapMarker.vue';
export default {
components: {
TMapMarker
}
};
</script>