记录–vue使用高德地图搜索选址&&拖拽选址
先放效果图
step1:安装依赖;引入AMap
申请key:在高德地图开放平台https://lbs.amap.com/dev/key/app控制台-应用管理-我的应用-新增应用,申请一个key
方法1
- 在index.html里引入
<!-- 引入高德,一定要在头部引入,因为高德需要预加载-->
<script src="//webapi.amap.com/maps?v=1.4.13&key=此处为申请的key值"></script>
<!-- 高德地图ui组件-->
<script src="//webapi.amap.com/ui/1.0/main.js"></script>
- 在build文件夹下的webpack.base.config.js配置,写在"module.exports={}’'里最底下,与"entry{}"平级
externals: {
'AMap': 'AMap',
'AMapUI': 'AMapUI'
}
- 在使用了用地图的组件中引入AMap,否则会报”AMap undefined”的错误
import AMap from 'AMap'
方法2:
- 在build文件夹下的webpack.base.config.js配置,写在"module.exports={}’'里最底下,与"entry{}"平级
externals: {
'AMap': 'AMap',
'AMapUI': 'AMapUI'
}
- 在assert文件夹里新建一个AMap.js
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.3&callback=initAMap&key=申请的key '
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
- 在使用了用地图的组件中引入MapLoader
import MapLoader from '../../../assets/AMap.js';
由于先使用的方法二,后面又引入了AMap,所以两种方法都使上了
现在进入主题
.html
<div style="margin-top: 20px">
<div style="height:500px;border:1px solid #dddddd;padding:0px 10px 10px 10px;border-radius:5px">
<p style="background-color: #eff5ff;padding: 8px;color: #01AAED;font-size: 16px">经纬度设置,找到位置,点击确定即可</p>
<div id="all" style="height:100%">
<div class="posInput">
<el-input style="width:100%"
id="tipinput"
class="form-control input-style"
type="text"
placeholder="请输入搜索地址"
prefix-icon="el-icon-search"
v-model="MapAdress"
@input="inputMapAdress">
</el-input>
</div>
<div id="allmap"></div>
<div class="posSubmit">
<el-input style="width:100%"
id="insureinput"
class="form-control input-style"
type="text"
v-model="insureAdress">
</el-input>
<el-button type="primary" size="large" style="padding: 10px 20px" @click="insureMapAdress">确定</el-button>
</div>
</div>
</div>
</div>
.js
注意点都在备注里了
<script>
import MapLoader from '../../../assets/AMap.js';
import Amap from "AMap";
export default {
name: 'demo',
data() {
return {
map: null,
thisPosition: {
location: '',
lng: '',
lat: ''
},
mapinitCode:0,//地理编码:1;地理逆编码:2
MapAdress:'',
insureAdress:'',
}
},
methods: {
inputMapAdress(e){
// console.log(e)
this.MapAdress = e
},
insureMapAdress(){//确定修改地址
console.log(this.insureAdress)
this.$confirm('此操作为修改地址, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
let data = {}
data.id=this.rowData.id;
data.longitute = this.thisPosition.lng
data.latitude = this.thisPosition.lat
data.address = this.insureAdress
updateCompanyAddress(data).then(res => {
if(res.data.code == 1){
this.$message({
message: '更新地址成功!',
type: 'success'
});
}else{
this.$message.error('修改失败');
}
})
})
},
mapMarker(longitute,latitude){ //指针
let that = this
//加载PositionPicker,loadUI的路径参数为模块名中 'ui/' 之后的部分
AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
var map = new AMap.Map('allmap',{
zoom:16
})
// 传入经纬度,设置地图中心点
if(that.mapinitCode == 1){
var position = new AMap.LngLat(longitute,latitude); // 标准写法
map.setCenter(position);
} else if(that.mapinitCode == 2){
var position = new AMap.LngLat(latitude,longitute); // 标准写法
map.setCenter(position);
}
var positionPicker = new PositionPicker({
mode:'dragMap',//设定为拖拽地图模式,可选'dragMap'、'dragMarker',默认为'dragMap'
map:map//依赖地图对象
});
//TODO:事件绑定、结果处理等
positionPicker.on('success', function(positionResult) {
console.log("positionResult",positionResult)
that.thisPosition.lng = positionResult.position.lng
that.thisPosition.lat = positionResult.position.lat
that.insureAdress = positionResult.address
});
positionPicker.on('fail', function(positionResult) {
// 海上或海外无法获得地址信息
console.log(`定位失败:` + positionResult)
});
positionPicker.start();
map.panBy(0, 1);
});
},
mapinit: function (longitute,latitude) { //经纬度定位
console.log("经纬度",longitute,latitude ,this.mapinitCode)
let that = this
MapLoader().then(AMap => {
var map = new AMap.Map("allmap", {
center: [longitute, latitude],//需求的城市的经度和 纬度
resizeEnable: true,
zoom: 16
})
AMap.plugin(['AMap.ToolBar', 'AMap.Scale','AMap.Autocomplete','AMap.PlaceSearch'],function(){
map.addControl(new AMap.ToolBar())
map.addControl(new AMap.Scale())
var autoOptions = {
city: "北京", //城市,默认全国
input: "tipinput"//使用联想输入的input的id(也就是上边那个唯一的id)
};
var autocomplete= new AMap.Autocomplete(autoOptions);
var placeSearch = new AMap.PlaceSearch({
city: '北京',
map: map
})
AMap.event.addListener(autocomplete, "select", function (e) {
//TODO 针对选中的poi实现自己的功能
console.log(e,e.poi.district,e.poi.address,e.poi.location.lng)
that.thisPosition.lng = e.poi.location.lng
that.thisPosition.lat = e.poi.location.lat
that.insureAdress = e.poi.district + e.poi.address
console.log(that.insureAdress)
var map = new AMap.Map('allmap',{
zoom:16
})
var position = new AMap.LngLat(e.poi.location.lng,e.poi.location.lat); // 标准写法
map.setCenter(position);
that.mapMarker(e.poi.location.lng,e.poi.location.lat)
});
});
that.mapMarker(longitute,latitude)
})
},
maplocal (address){ //地理逆编码
let that = this
MapLoader().then(AMap => {
AMap.plugin(['AMap.Geocoder'], function () {
let geocoder = new AMap.Geocoder();
geocoder.getLocation(address, (status, result) => {
console.log(address);
if (status === 'complete' && result.geocodes.length) {
console.log(result)
const lnglat = result.geocodes[0].location;
const lat = lnglat.lat;
const lng = lnglat.lng;
that.mapinit(lat, lng) //tips:使用地理逆编码,此时解析出的经纬度位置也应逆换
} else {
console.log(result)
}
});
})
})
},
},
mounted() {
//我这里的经纬度是从路由上带过来的,如果路由上有经纬度,取经纬度;
//如果路由上没有经纬度,则取路由上带过来的详细地址(address)使用地理逆编码转换为经纬度定位到地图上
//tips:使用地理逆编码,此时解析出的经纬度位置也应逆换
if(this.$route.query) {
if(this.$route.query.rowData.longitute){
console.log("有经纬度")
this.mapinitCode = 1;
this.mapinit(this.$route.query.rowData.longitute,this.$route.query.rowData.latitude)
}else{
console.log("无经纬度")
this.mapinitCode = 2;
this.maplocal(this.$route.query.rowData.address)
}
}
}
}
</script>
.css
<style scoped>
#all{
position: relative;
}
#allmap{
width: 100%; height: calc(100% - 40px);
font-family: "微软雅黑";
border:1px solid pink;
}
.posInput{
position: absolute; z-index: 1;
width: 80%;
margin-top: 20px; margin-left: 10%;
}
.posSubmit{
position: absolute; z-index: 1; bottom: 56px;
margin-left: 10%;
width: 80%;
display: flex; justify-content: flex-start; align-items: center;
}
</style>