主要需求是: 1.通過搜索地址獲取坐標經緯度, 2.通過點擊地圖上的位置獲取地址同時獲取坐標經緯度 使用了地址解析和反地址解析 npm安裝騰訊地圖 騰訊官方並沒有在npm上發布騰訊地圖插件,所以找到一個別人寫的,可以直接調用騰訊地圖javascript方法 鏈接:https://www.npmjs.com/package/qqmap npm install qqmap --save 在組件中引入 import maps from "qqmap"
地圖 DOM 元素
<div class="map">
<el-input v-model="addressKeyword" placeholder="請輸入地址來直接查找相關位置" clearable style="margin-bottom:20px">
<el-button slot="append" icon="el-icon-search" @click="getAddressKeyword"></el-button>
</el-input>
<div id="container" style="width:100%; height:300px"></div>
</div>
data:{ //騰訊地圖 map: null, getAddress: null, getAddCode: null, addressKeyword: "" }
由於在使用的把地圖DOM放在了可顯示隱藏的盒子里,導致了地圖不顯示的問題,(showModal是一個控制顯示隱藏的變量;newValue是watch監聽的新值)
故:
watch: {
showModal: function(newValue) {
if (newValue) {
this.init();
}
}
},
初始化地圖
methods: {
//初始化地圖
init() {
var that = this;
maps.init("W3YBZ-NW734-APUUL-XQTC4-76L2T-NCF70", () => {
var myLatlng = new qq.maps.LatLng(22.547931568083015, 114.1306221485138);
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: qq.maps.MapTypeId.ROADMAP
};
that.map = new qq.maps.Map(
document.getElementById("container"),
myOptions
);
//獲取點擊后的地址
qq.maps.event.addListener(that.map, "click", function(event) {
// 獲取點擊后的地圖坐標
that.shopInfo.lng = event.latLng.getLng();
that.shopInfo.lat = event.latLng.getLat();
that.getAddressCode();
});
//調用地址顯示地圖位置並設置地址
that.getAddress = new qq.maps.Geocoder({
complete: function(result) {
that.map.setCenter(result.detail.location);
console.log(result.detail.location)
that.shopInfo.lng = result.detail.location.lng;
that.shopInfo.lat = result.detail.location.lat;
var marker = new qq.maps.Marker({
map: that.map,
position: result.detail.location
});
}
});
//通過坐標來顯示地圖地址
that.getAddCode = new qq.maps.Geocoder({
complete: function(result) {
that.addressKeyword = result.detail.address;
}
});
});
},
//通過地址獲得位置
getAddressKeyword() {
//通過getLocation();方法獲取位置信息值
this.getAddress.getLocation(this.addressKeyword);調用自帶的接口
},
// 通過坐標獲得地址
getAddressCode() {
var lat = parseFloat(this.shopInfo.lat);
var lng = parseFloat(this.shopInfo.lng);
var latLng = new qq.maps.LatLng(lat, lng);
//調用獲取位置方法
this.getAddCode.getAddress(latLng);
},
