1、申请key
天地图地图服务对所有用户开放。使用本组服务之前,需要申请Key
2、引入API
地图API是由JavaScript语言编写的,您在使用之前需要通过<script>标签将API引用到页面中:
<script src="http://api.tianditu.gov.cn/api?v=4.0&tk=您的密钥" type="text/javascript"></script>
在vue项目中,我们在public文件夹的index.html中引入天地图的api文件
<!DOCTYPE html>
<html lang="zh-CN">
<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">
<script defer src="//static.gdzwfw.gov.cn/mhyy/browser-upgrade/index.js"></script>
<script type="text/javascript" src="http://api.tianditu.gov.cn/api?v=4.0&tk=你申请的key"></script>
</head>
<body>
<noscript>
<strong>We're sorry but aba-init-vue doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="root"></div>
</body>
</html>
3、在vue页面中,创建一个tiandiMap.vue页面,初始化地图,代码如下:
<template>
<div>
<div id="divwxMap" class="divwxMap" style="width: 100%;height: 580px;"></div>
<div style="margin-top:10px;width:100%">
<label for="">选中的地址:</label>
<gd-input
style="width:88%"
v-model="address">
</gd-input>
</div>
</div>
</template>
<script type="text/javascript">
import { mapActions } from 'vuex';
export default {
components: {
},
data () {
return {
wxMap: '',
address: '',
markerTool: '',
addrResult: {},
};
},
mounted () {
this.initwxMap();
},
methods: {
...mapActions([
'getGeocoder',
]),
// 初始化天地图
initwxMap () {
// vue项目需要先声明 T = window.T
let T = window.T;
this.wxMap = new T.Map('divwxMap'); // div的id
// 传参中心点经纬度,以及放大程度,最小1,最大18
this.wxMap.centerAndZoom(new T.LngLat(113.86942, 35.30416), 18);
var cp = new T.CoordinatePickup(this.wxMap, { callback: this.getLngLat });
cp.addEvent();
},
getLngLat (lnglat) {
let T = window.T;
console.log('获取的经纬度');
const x = lnglat.lng.toFixed(6);
const y = lnglat.lat.toFixed(6);
this.wxMap.clearOverLays(); // 清空原来的标注点
let point = new T.LngLat(x, y);
let marker = new T.Marker(point);
this.wxMap.addOverLay(marker); // 添加标注点
this.getGeocoderFun(x, y);
},
// 根据经纬度获取地址
async getGeocoderFun (lon, lat) {
this.$loading.show('查询中...');
const query = {
postStr: {
lon,
lat,
ver: '1',
},
type: 'geocode',
tk: '7b733691924fcd55d8724722172a0664',
};
try {
const res = await this.getGeocoder({ query });
this.$loading.hide();
if (res.status === '0') {
const result = res.result;
this.address = result.formatted_address;
this.addrResult = result;
}
}
catch (e) {
this.$loading.hide();
}
},
getAddress () {
return this.addrResult;
},
},
};
</script>
<style lang="stylus" scoped>
</style>
效果: