1、首先引入plugin
//webapi.amap.com/maps?v=1.4.15&key=000&plugin=AMap.CustomLayer,AMap.Geocoder
2、mixin
import { uuid } from '@/utils/utils';
export default {
data() {
return {
map: null,
mapStyle: 'amap://styles/bcb8c05d5306c3e9004a513721f93262', //自定义地图样式
zoom: 13, // 地图缩放等级
mapId:'map-' + uuid()
}
},
props: {
},
created() {
},
mounted() {
this.initMap()
},
destroyed(){
this.map && this.map.destroy();
},
methods: {
initMap(){
// 绘制地图
this.map = new AMap.Map(this.mapId, {
mapStyle: this.mapStyle,
zoom: this.zoom,
viewMode: '2D',
resizeEnable:true
})
},
// 获取当前的定位
getLocation(){
return new Promise((resolve,reject)=>{
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
// 是否使用高精度定位,默认:true
enableHighAccuracy: true,
// 设置定位超时时间,默认:无穷大
timeout: 10000,
// 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
buttonOffset: new AMap.Pixel(10, 20),
// 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
zoomToAccuracy: true,
// 定位按钮的排放位置, RB表示右下
buttonPosition: 'RB',
showMarker: false,
showCircle: false,
})
geolocation.getCurrentPosition()
AMap.event.addListener(geolocation, 'complete', onComplete)
AMap.event.addListener(geolocation, 'error', onError)
function onComplete (data) {
// data是具体的定位信息
resolve(data);
}
function onError (data) {
// 定位出错
resolve(data);
}
})
})
},
// 根据经纬度获取详细地理信息;比如省市区街道
getCurPosiInfo({lng,lat}){
return new Promise((resolve,reject)=>{
var lnglat = [ lng,lat]
var geocoder = new AMap.Geocoder({
radius: 1000 //范围,默认:500
});
geocoder.getAddress(lnglat, (status, result)=>{
if (status === 'complete' && result.regeocode) {
resolve(result.regeocode)
}else{
resolve()
}
});
})
},
/**
*搜索服务
*/
onSearchInput() {
let keywords = this.searchVal;
AMap.plugin("AMap.Autocomplete", () => {
let autoOptions = {
city: this.city,
citylimit: true,
};
let autoComplete = new AMap.Autocomplete(autoOptions);
autoComplete.search(keywords, (status, result) => {
// 搜索成功时,result即是对应的匹配数据
if (status == "complete") {
this.searchList = result.tips;
this.searchList = this.searchList.map((res) => {
res.nameNew = res.name;
if (keywords) {
const replaceReg = new RegExp(keywords, "g");
const replaceString =
'<span class="search-text">' + keywords + "</span>";
res.nameNew = res.nameNew.replace(replaceReg, replaceString);
}
return res;
}).filter(res=>res.location);
}else{
this.searchList = [];
}
this.visible = true;
});
});
},
// 获取城市的中心经纬度
getLnglat(cityName){
return new Promise((resolve,reject)=>{
var geocoder = new AMap.Geocoder({
city: cityName
});
geocoder.getLocation(cityName, (status, result)=>{
if (status === 'complete' && result.info === 'OK') {
console.log(result);
resolve(result)
}else{
resolve()
}
});
})
}
},
}