ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

在vue项目中使用天地图,点击可打点,搜索打点组件封装

2026/9/19 2:08:41 拓冰建站 浏览量
在vue项目中使用天地图,点击可打点,搜索打点组件封装

一、在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>