工具类方法:
export default { load(callback) { if (window.AMap) { callback() } else { // 载入高德地图和UI组件 var script = document.createElement('script') script.type = 'text/javascript' script.async = true script.src = 'https://webapi.amap.com/maps?v=1.4.4&key=****************&callback=initAmap' document.body.appendChild(script) window.initAmap = () => { callback() } } }, defaultOption: { panel: 'panel' }}
使用:
根据地址获取地址的经纬度:
amap.load(() => { const map = new AMap.Map('map'); map.plugin('AMap.Geocoder', () => { var address = '广东省深圳市福田区'; var geocoder = new AMap.Geocoder({}); // 获取定位信息 geocoder.getLocation(address, function (status, result) { if (status === 'complete' && result.geocodes.length) { // var lnglat = result.geocodes[0].location; console.log(result.geocodes[0]) } console.log(result) }); }); });
获取当前定位:
amap.load(() => { const maps = new AMap.Map('map'); const _this = this; map.plugin('AMap.Geolocation', function() { _this.geolocation = new AMap.Geolocation({ useNative: true, timeout: 10000 }); // 获取定位信息 _this.geolocation.on('complete', function(data) { _this.isClock = true; _this.$vux.loading.hide(); _this.clockData.longitude = data.position.lng; _this.clockData.latitude = data.position.lat; _this.clockData.location = data.formattedAddress; _this.clockData.city = data.addressComponent.city || data.addressComponent.province; _this.clockTime = _this.formatDate(new Date().getTime()); }); _this.geolocation.on('error', function(data) { console.log(data); _this.$vux.toast.show('获取定位失败!'); _this.$vux.loading.hide(); _this.islock = false; }); _this.geolocation.getCurrentPosition(); });});