高德地图开发者开放平台文档
<!-- 地图组件 -->
<template>
<view class="store-map" id="app-store-map" ref="storeMap"></view>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import appConfig from "@/config";
import { throttle } from "@/util/utils";
export default {
data() {
return {
/** 地图实例 */
map: null,
/** 关键词搜索实例 */
autoComplete: null,
/** poi经纬度搜索实例 */
placeSearch: null,
/** 地理位置实例 */
geolocation: null,
/** 插件列表 */
plugins: [
"AMap.Geolocation",
"AMap.PlaceSearch",
"AMap.AutoComplete",
"AMap.LngLat",
],
};
},
created() {
window._AMapSecurityConfig = {
securityJsCode: appConfig.securityJsCode,
};
},
mounted() {
this.initMap();
},
methods: {
initMap() {
AMapLoader.load({
key: appConfig.aMapKey, // 申请好的Web端开发者Key,首次调用 load 时必填
version: "2.0", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: this.plugins,
})
.then((AMap) => {
this.placeSearch = new AMap.PlaceSearch({
city: "全国",
type: "",
pageIndex: 1,
pageSize: 10,
extensions: "all",
datatype: "poi", // 搜索类型
citylimit: true, // 强制在设置的城市中搜索
});
this.autoComplete = new AMap.AutoComplete({
extensions: "all",
datatype: "poi", // 搜索类型
citylimit: true,
});
this.geolocation = new AMap.Geolocation({
// 是否使用高精度定位
enableHighAccuracy: true,
// 定位超时时间
timeout: 10000,
// 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
zoomToAccuracy: false,
needAddress: true,
});
const map = new AMap.Map("app-store-map", {
viewMode: "2D", //是否为3D地图模式
zoom: 14, //初始化地图级别
});
this.map = map;
// 地图移动结束后根据中心点查询
map.on("complete", () => {
this.getTipsByCurrentPos();
this.$emit("loadEnd")
});
map.on("moveend", () => {
this.getTipsByPos(map.getCenter());
});
})
.catch((e) => {
uni.showToast({ title: "地图绘制失败", icon: "error" });
});
},
getPosLngLat(center) {
const { lng, lat } = center;
return new AMap.LngLat(lng, lat);
},
/** 根据输入内容搜索附近内容 */
getTipsByKeywords(keyWords) {
if (!keyWords.trim()) {
this.getTipsByCurrentPos();
return;
}
this.autoComplete.search(keyWords, (_status, result) => {
const { tips } = result;
const firstTip = tips[0];
if (firstTip) {
const { lng, lat } = firstTip.location;
this.map.panTo([lng, lat]);
}
this.emitThrottle(tips);
});
},
/** 根据地图中心经纬度查询附近内容 */
getTipsByPos(centerPos) {
this.placeSearch.searchNearBy(
"",
this.getPosLngLat(centerPos),
10000,
(_status, result) => {
const tips = result.poiList.pois || [];
this.emitThrottle(tips);
},
);
},
/** 根据当前定位搜索附近内容 */
getTipsByCurrentPos() {
this.geolocation.getCurrentPosition((status, result) => {
const { lng, lat } = result.position;
this.map.panTo([lng, lat]);
this.getTipsByPos(result.position);
});
},
/** 节流回调 */
emitThrottle(tips) {
throttle(() => {
this.$emit("tipsChange", tips);
}, 1500);
},
},
};
</script>
<style lang="scss" scoped>
.store-map {
height: 100%;
}
</style>