原本使用的是地图JavascriptAPI v2的服务类API,但是因系统架构改造,已经在 2024-06-07日关闭,为了不影响使用,切换到功能更为丰富、稳定的 WebServiceAPI
WebServiceAPI的描述:
腾讯地图WebService API 是基于HTTPS/HTTP协议的数据接口。
开发者可以使用任何客户端、服务器和开发语言,按照腾讯地图WebService API规范,按需构建HTTPS请求,并获取结果数据(目前支持JSON/JSONP方式返回),需要申请开发者密钥(Key):(key是调用API的身份标识,作为必填参数之一传递给API接口)
1、地图的显示
变量的声明
data() {
return {
geocoder: null,
map: null,
marker: null,
lonlataddress: "",
longitude: "", //经度
latitude: "", //纬度
};
},
①首先得有一个容器
<div id="mapContainer" style="width:100%;height:400px;"></div>
②初始化地图
initMap() {
var that = this;
that.map = new qq.maps.Map(document.getElementById("mapContainer"), {
zoom: 20
});
that.marker = new qq.maps.Marker({
map: that.map,
draggable: true
});
if (this.title === "新增") {
//新增时--需要用到是地址解析
//由文字地址到经纬度的转换能力,并同时提供结构化的省市区地址信息
that.map.setCenter(new qq.maps.LatLng(39.916527, 116.397128));
// 默认打开地图显示的地址-->北京
that.setMarkerAndGeocoderEvents();
} else {
//编辑时--需要用到的是逆地址解析
//提供由经纬度到文字地址及相关位置信息的转换
var lonlat = this.form.lonlat.split(",");
var position = new qq.maps.LatLng(
parseFloat(lonlat[0]),
parseFloat(lonlat[1])
);
that.map.setCenter(position);
that.marker.setPosition(position);
that.reverseGeocode(position);
that.setMarkerAndGeocoderEvents();
}
},
③地址解析相关代码
codeAddress() {
var that = this;
var address = encodeURIComponent(this.lonlataddress);
var key = "xxxxZ-xxxxG-xxxxD-xxxxH-xxxxZ-xxxxZ";
var url = `https://apis.map.qq.com/ws/geocoder/v1/?address=${address}&key=${key}&output=jsonp`;
this.$jsonp(url)
.then(response => {
console.log("response", response);
var result = response.result;
var location = result.location;
that.form.lonlat = `${location.lat},${location.lng}`;
that.map.setCenter(new qq.maps.LatLng(location.lat, location.lng));
that.marker.setPosition(
new qq.maps.LatLng(location.lat, location.lng)
);
that.lonlataddress =
result.address_components.province +
result.address_components.city +
result.address_components.district +
result.title;
//强制组件及其子组件重新渲染
// that.$forceUpdate();
})
.catch(err => {
alert("出错了,请输入正确的地址!!!");
});
},
四:逆地址解析
reverseGeocode(position) {
var that = this;
var location = `${position.lat},${position.lng}`;
var key = "xxxxZ-xxxxG-xxxxD-xxxxH-xxxxZ-xxxxZ";
var url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${location}&key=${key}&get_poi=1&output=jsonp`;
this.$jsonp(url)
.then(response => {
console.log("reverseGeocode--response", response);
var result = response.result;
var address = result.address;
that.lonlataddress = address;
that.form.lonlat = location;
})
.catch(error => {
alert("出错了,请输入正确的地址!!!");
});
},
五:拖拽图标获取经纬度
setMarkerAndGeocoderEvents() {
var that = this;
qq.maps.event.addListener(that.marker, "dragend", function() {
var position = that.marker.getPosition();
that.reverseGeocode(position);
});
},
最后就是运行显示地图了
created(){
this.initMap()
}
注:使用$jsonp发起请求是为了避免发生跨域问题
安装和引入vue-jsonp:
使用npm install vue-jsonp安装vue-jsonp库。
在主入口文件(例如main.js)中引入并使用vue-jsonp
main.js
import { VueJsonp } from "vue-jsonp";
Vue.use(VueJsonp);
版权归原作者 zengkeai 所有, 如有侵权,请联系我们删除。