vue-高德地圖-點選地圖-獲取省市區-獲取經緯度-獲取街道地址
阿新 • • 發佈:2021-01-31
技術標籤:javascripthtml5node.jscss3typescript
1.html 首頁要有註冊的高德地圖KEY 申請註冊的方式百度一下就OK啦 我這個vue 是針對3.0以後的cli3 以後的 預設進入 是自動定位獲取當前位置 和 經緯度的。
1.<scripttype="text/javascript"src="http://webapi.amap.com/maps?v=1.4.15&key=你的key&plugin=AMap.Geocoder"></script>
效果圖是下面的,寫這個功能花了一天半的時間 有引入過別人的程式碼 然後自己再優化了一部分。
2.下載安裝amp main.js配置 還要vue.config.js 的配置
npm install -S vue-amap // 下面是main.js配置 import AMap from 'vue-amap' Vue.use(AMap) AMap.initAMapApiLoader({ key: 你的key, plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PlaceSearch', 'AMap.Geolocation', 'AMap.Geocoder'], v: '1.4.4', })
// 這是vue.config.js 配置 將AMap作為全域性變數 module.exports = { publicPath: "./", chainWebpack: (config) => { config.resolve.alias .set('@', resolve('src')) .set('@components', resolve('src/components')) .set('@img', resolve('src/assets/imgs')) }, configureWebpack: { externals: { 'AMap': 'AMap' } } }
3.然後寫子元件 父元件呼叫 這是一個完整子元件 可以直接呼叫
<template>
<div class="map-box" :style="{ width: width, height: height }">
<div id="amap" class="amap"></div>
<div class="detail">
<p>經度:{{point ? point[0] : '-'}}</p>
<p>緯度:{{point ? point[1] : '-'}}</p>
<p>地址:{{address}}</p>
<button size="mini" class="btnmap" @click="commit">確定</button>
</div>
</div>
</template>
<script>
import AMap from "AMap";
export default {
props: {
width: { type: String, default: "100%" },
height: { type: String, default: "400px" }
},
data() {
return { address: "", point: this.lnglat, marker: "" };
},
mounted() {
this.init(this.point);
},
methods: {
// 初始化
init() {
// 地圖例項物件 (amap 為容器的id)
let amap = new AMap.Map("amap", {
resizeEnable: true,
zoom: 15
});
// 注入外掛(定位外掛,地理編碼外掛)
amap.plugin(["AMap.Geolocation", "AMap.Geocoder"]);
// 定位
this.currentPosition(amap);
let that = this;
amap.on("click", function(e) {
//地圖被點選的時候
amap.remove(that.marker);
let lnglat = [e.lnglat.lng, e.lnglat.lat];
amap.setCenter(lnglat);
that.addMark(amap, lnglat);
that.point = [e.lnglat.lng, e.lnglat.lat];
that.getAddress([e.lnglat.lng, e.lnglat.lat]);
});
},
// 定位
currentPosition(map) {
// 獲取地圖的位置
// 沒有傳入座標點,則定位到當前所在位置
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true,
timeout: 10000,
zoomToAccuracy: true,
buttonPosition: "RB"
});
geolocation.getCurrentPosition((status, result) => {
if (status === "complete") {
let points = [result.position.lng, result.position.lat];
map.setCenter(points); // 設定中心點
this.addMark(map, points); // 新增標記
// 存下座標與地址
this.point = points; // 複製給展示html頁面
this.getAddress(points); // 傳入座標 獲取地址
} else {
console.log("定位失敗", result);
}
});
},
// 新增標記 就是感嘆號標記
addMark(map, points) {
this.marker = new AMap.Marker({
map: map,
position: points,
draggable: true, // 允許拖動
cursor: "move",
raiseOnDrag: true,
title: "中心"
});
this.marker.on("dragend", e => {
console.log(e);
let position = this.marker.getPosition();
// 存下座標與地址
this.point = [position.lng, position.lat];
this.getAddress([position.lng, position.lat]);
});
},
// 根據座標返回地址(逆地理編碼)
getAddress(points) {
let geocoder = new AMap.Geocoder({ radius: 1000 });
geocoder.getAddress(points, (status, result) => {
if (status === "complete" && result.regeocode) {
let s_addr =
result.regeocode.addressComponent.province +
"-" +
result.regeocode.addressComponent.city +
"-" +
result.regeocode.addressComponent.district;
let addreesd = result.regeocode.formattedAddress; // 全部地址名稱
let houzhi = addreesd.substring(s_addr.length); // 獲取具體街道
console.log(s_addr);
console.log(houzhi);
console.log(addreesd);
this.address = s_addr + "," + houzhi;
}
});
},
commit() {
this.$emit("location", this.point, this.address);
}
}
};
</script>
<style lang="scss" >
.map-box {
box-sizing: border-box;
background-color: #ddd;
padding-top: 10px;
&:after {
content: "";
display: block;
clear: both;
}
.amap,
.detail {
float: left;
height: 100%;
}
.amap {
width: 100%;
}
.detail {
width: 100%;
background-color: #fff;
padding: 0 15px;
border-left: 1px solid #eee;
box-sizing: border-box;
word-wrap: break-word;
height: 20%;
top: 0px;
position: absolute;
p {
margin-top: 10px;
}
}
.btnmap {
width: 100%;
padding: 5px 0;
color: #fff;
cursor: pointer;
background-color: #409eff;
border: none;
border-radius: 3px;
margin-top: 5px;
&:hover {
background-color: #66b1ff;
}
}
}
</style>
4.寫父元件呼叫的程式碼 引入子元件 子元件在父元件裡面顯示。
// 這個是地圖顯示 isditu 控制是否展示地圖
<div class="box" v-show="isditu">
<xmap width="100%" height="100%" @location="location"></xmap>
</div>
// 這個是點選事件 觸發 控制地圖顯示
<div class="dandee">
<div class="danone">所在區域</div>
<div class="dantwo">
<el-input v-model="s_addr" placeholder="請選擇所在區域" @click="xuanzeditu"></el-input>
</div>
<img src="../../assets/imgs/xingxing.png" class="xingxing" />
<img src="../../assets/imgs/jinru.png" @click="xuanzeditu" class="jinrud" />
</div>
<div class="dandee">
<div class="danone">詳細地址</div>
<div class="dantwo">
<el-input v-model="s_house_number" @change="changedd" placeholder="請輸入街道門牌號"></el-input>
</div>
<img src="../../assets/imgs/xingxing.png" class="xingxing" />
</div>
</div>
//js 寫法
import xmap from "./ceshimap"; //引入子元件
import axios from "axios"; // vue axios安裝我就不說了
export default {
components: {
xmap
},
data() {
return {
isditu: false,
provinceValue: "",
cityValue: "",
regionValue: "",
s_addr:"",
s_house_number: "",
s_latitude :"",
s_longitude :"",
};
},
methods: {
// 這個是點選子元件裡面的確定
location(point, address) {
this.isditu = false;
this.s_latitude = point[1];
this.s_longitude = point[0];
let s_addrs = address.split(",")[0];
this.provinceValue = s_addrs.split("-")[0]; //省會
this.cityValue = s_addrs.split("-")[1]; // 城市
this.regionValue = s_addrs.split("-")[2]; // 區域
this.s_addr = this.provinceValue + this.cityValue + this.regionValue; //省市區 拼接
console.log(address.split(",")[1]);
this.s_house_number = address.split(",")[1]; // 門牌號
},
// 這個是點選父元件選擇區域 顯示地圖
xuanzeditu() {
this.isditu = true;
},
// 注意如果 客戶修改具體的門牌號 那麼我們需要重新獲取經緯度
changedd() {
axios
.get("https://restapi.amap.com/v3/geocode/geo", { //這個但是呼叫官方的方法 將地址解析成經緯度
params: {
key: 你的key,
address:
this.provinceValue +
this.cityValue +
this.regionValue +
this.s_house_number
}
})
.then(response => {
console.log(response.data.geocodes[0].location.split(","));
let shuzu = response.data.geocodes[0].location.split(",");
this.s_latitude = shuzu[1];
this.s_longitude = shuzu[0];
})
.catch(function(error) {
// 請求失敗處理
console.log(error);
});
},
}
}