/*
* 异步创建script标签
*/
export default function MapLoader () {
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var script = document.createElement('script')
script.type = 'text/javascript'
script.async = true
script.src = 'http://webapi.amap.com/maps?v=1.4.15&callback=initAMap&key=高德申请的key'
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
vue
文件中使用:
import MapLoader from '../../config/initMap.js'
<template>
<div class="container">
<div class="maploader">
<div id="mymap" class="map"></div>
</div>
</div>
</template>
<script>
import MapLoader from '../../config/initMap.js'
export default {
components: {
},
name: 'maploader',
data() {
return {
map: null
};
},
mounted () {
let that = this
MapLoader().then(AMap => {
console.log('地图加载成功')
that.map = new AMap.Map("mymap", {
resizeEnable: true,
center: [117.000923, 36.675807],
zoom: 11
});
}, e => {
console.log('地图加载失败' ,e)
})
},
};
</script>
<style lang="scss">
.map {
height:640px;
width:100%;
}
</style>
如何使用定位,点击事件,打点功能:
// 初始化地图
intitMap() {
let that = this;
MapLoader().then(AMap => {
let map = new AMap.Map("gaodemap", {
resizeEnable: true,
center: [113.364476, 36.675807],
zoom: 15
});
that.map = map;
// 定位信息
that.getLocation();
}, e => {
uni.showToast({
title: '地图加载失败',
icon: 'none'
});
})
},
// 获取定位信息
getLocation() {
let map = this.map;
let that = this;
map.plugin('AMap.Geolocation', function() {
let geolocation = new AMap.Geolocation({
//是否使用高精度定位,默认:true
enableHighAccuracy: false,
//超过5秒后停止定位,默认:无穷大
timeout: 5000,
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
//返回定位信息
AMap.event.addListener(geolocation, 'complete', function(res) {
// 获取当前的经纬度
that.latitude = res.position.lat;
that.longitude = res.position.lng;
that.myLocationAddress = res.formattedAddress;
that.map = map;
uni.showToast({
title: '获取定位信息成功',
icon: 'none'
});
});
//返回定位出错信息
AMap.event.addListener(geolocation, 'error', function(err) {
uni.showToast({
title: '获取地址失败,将导致部分功能不可用',
icon: 'none'
});
});
});
},
// 给地图增加点击事件
setMapClickEvent() {
this.map.on('click', function(e) {
alert(1)
});
},
// 给地图增加标记
setMarkToMap(lat, lng, address) {
console.log(lat);
console.log(lng)
let marker = new AMap.Marker({
map: this.map,
position: [lat, lng]
})
marker.markOnAMAP({
name: address,
position: marker.getPosition()
});
// marker.setLabel({
// //修改label相对于maker的位置
// offset: new AMap.Pixel(20, 15),
// content: address
// });
// marker.on('click', function(e) {
// marker.markOnAMAP({
// name: address,
// position: marker.getPosition()
// })
// })
},