持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第12天,点击查看活动详情
效果图
总体代码
<template>
<div style="width: 85%; height: 500px">
<div>
<el-input
style="width: 60%"
v-model="inputObject.userInput"
:id="inputObject.inputId"
placeholder="请输入你要查找的关键词"
type="text"
></el-input>
<el-button type="primary" @click="send">搜索</el-button>
</div>
<div id="container"></div>
</div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getStation } from "@/api/pile/station.js";
window._AMapSecurityConfig = {
securityJsCode: "829b6b73f84682c2eb982eaa47a745b8",
};
export default {
data() {
return {
map: null,
autoOptions: {
input: "",
},
inputObject: {
userInput: "",
inputId: "searchInput",
},
searchPlaceInput: "",
auto: null,
placeSearch: "",
stationId: this.$route.params.id,
};
},
methods: {
// 搜索
send() {
this.autoOptions.input = this.inputObject.inputId;
this.searchPlaceInput = this.inputObject.userInput;
// console.log(this.lng, this.lat);
},
queryStationInfo() {
getStation(this.stationId).then((response) => {
this.lat = response.data.stationLat;
this.lng = response.data.stationLng;
console.log(this.lat, this.lng);
this.initMap(this.lat, this.lng);
});
},
initMap(lat, lng) {
// console.log(lat, lng);
AMapLoader.load({
key: "61436c9c789d301a5b73853d176710cf", // 申请好的Web端开发者Key,首次调用 load 时必填
version: "1.4.15", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: ["AMap.AutoComplete", "AMap.PlaceSearch"], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
})
.then((AMap) => {
this.map = new AMap.Map("container", {
//设置地图容器id
viewMode: "3D", //是否为3D地图模式
zoom: 5, //初始化地图级别
center: [+lng, +lat], //初始化地图中心点位置
});
// console.log("map", this.map);
// 设置鼠标的样式
this.map.setDefaultCursor("pointer");
// 点标记
let marker = new AMap.Marker({
position: new AMap.LngLat(+lng, +lat),
});
// 将创建的点标记添加到已有的地图实例
this.map.add(marker);
AMap.plugin("AMap.AutoComplete", function () {
auto = new AMap.AutoComplete(this.autoOptions);
//构造地点查询类
auto.on("select", this.select);
});
this.placeSearch = new AMap.PlaceSearch({
map: this.map,
});
})
.catch((e) => {
console.log(e);
});
},
select(e) {
this.placeSearch.search(e.poi.name); //关键字查询查询
},
},
mounted() {
//DOM初始化完成进行地图初始化
this.queryStationInfo();
},
created() {
this.send();
},
watch: {
searchPlaceInput(newValue) {
if (newValue != null) {
console.log(newValue);
this.placeSearch.search(newValue);
this.map.setZoom(16, true, 1);
}
},
},
};
</script>
<style lang="scss">
#container {
padding: 0px;
margin: 0px;
width: 100%;
height: 90%;
}
</style>
踩坑经验
第一个坑就是
<template>
<div>
<div id="contauner"></div>
</div>
</template>
这里面就有一个坑,那就是地图容器,用div包裹时,要给父div设置宽高,否则,地图不报错、效果也不出来
第二个坑
center/position:【lng,lat】// (1开头的,3开头的) // 之前一直的是 lat,lng 导致地图地位到海里,最后发现顺序写反了
lng、lat分别代表经度、纬度值
第三个坑
就是要传参,如果这里面不传参数,会报 ReferenceError: lng is not defined
第四个
请求方式要用 promise.then的方法,不要用 async await
第五个
版本问题
不要使用2.0版本的