Skip to content
On this page
🎨 作者:Jacinda 📔 阅读量:

高德地图使用总结

由于项目需要,本来以为可以直接使用高德API就能在小程序上嵌入地图啥的,结果不行,无论用哪个第三方API,map组件的底图还是腾讯,心累。

索性,就单独用 uniapp 开发了一个H5页面,作为高德地图页面,然后再嵌入进行小程序 web-view 中。

下面是用到的一些方法,对此进行一个整理

地图初始化

  1. 正常需要地图key的,都需要先去官网申请。
  2. 安装并引入 @amap/amap-jsapi-loader
  3. 配置key

引入 与 配置

javascript
import AMapLoader from '@amap/amap-jsapi-loader';

let amapKey = 'xxx';
let map = null;

window._AMapSecurityConfig = {
    securityJsCode: "xxxx",
};

地图组件

html
<template>
    <div id="map-container" style="width: 100vw; height: 100vh;"></div>
</template>
javascript
// 地图初始化
initMap() {
    AMapLoader.load({
        key: amapKey,
        version: '2.0',
        plugins: [
            'AMap.Geolocation',
            'AMap.AutoComplete',
        ]
    }).then(AMap => {
        // 创建卫星图层
        let satellite = new AMap.TileLayer.Satellite();
        // 创建路网图层
        let roadNet = new AMap.TileLayer.RoadNet();
        // 地图实例化
        map = new AMap.Map("map-container", {
            viewMode: '2D', //地图模式
            zoom: 17, //初始化地图层级
            zooms: [2, 20], //地图显示的缩放级别范围
            center: [117.017316, 25.076163], //初始地图中心经纬度
            terrain: true,
            layers: [satellite,roadNet], //地图图层的数组
            resizeEnable: true
        });
        // 获取当前定位
        this.getLocation();
        // 监听地图的点击事件
        map.on("click", this.clickMapHandler);
    }).catch(e => {
        console.error(e)
    });
}

获取当前定位

javascript
// 获取当前定位
getLocation() {
    let that = this;
    let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, // 是否使用高精度定位,默认:true
        timeout: 10000, // 超过10秒后停止定位,默认:无穷大
        maximumAge: 0, // 定位结果缓存0毫秒,默认:0
        convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
        showButton: true, // 显示定位按钮,默认:true
        buttonPosition: 'RB', // 定位按钮停靠位置,默认:'LB',左下角
        buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
        showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
        showCircle: false, // 定位成功后用圆圈表示定位精度范围,默认:true
        panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
        zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
    });
    map.addControl(geolocation);
    geolocation.getCurrentPosition(function(status, result) {
        if (status == "complete") {
            onComplete(result);
        }
    });
    function onComplete(data) {
        that.location.lat = data.position.lat;
        that.location.lng = data.position.lng;
    }
},

搜索关键词补充

  1. 通过 @input 对输入框进行监听
  2. 获取到关键词之后,调用 AMap.AutoCompletesearch 方法,获取回调值
  3. 把返回结果赋值,在页面上渲染
html
<input 
    type="text" 
    placeholder="请输入搜索内容" 
    :value="searchKey" 
    @input="handleSearch"
/>
javascript
// 监听输入内容,获取搜索结果
handleSearch(e) {
    console.log(e.detail.value,'----监听输入内容')
    let searchKey = e.detail.value;
    ...
    this.mapSearch(searchKey).then( res => {
        console.log(res,'-----返回结果')
        if(res.tips.length > 0) {
            this.searchResultList = res.tips;
        }
    })
    ...
},
// 关键词补充接口
mapSearch(keyword){
    let promise = new Promise(function(resolve, reject) {
        // 调用接口
        let autoComplete = new AMap.AutoComplete({
            city: '龙岩市',
            citylimit: true,
            datatype: 'poi'
        });
        autoComplete.search(keyword, function (status, result) {
            if (status == "complete") {
                resolve(result)
            } else {
                reject(result)
            }
        });
    });
    return promise
},

设置中心点位

javascript
setMapCenter(lng,lat) {
    let center = new AMap.LngLat(lng, lat);
    map.setCenter(center);
},

地图点击事件

  1. 监听 click 事件,获取点击的坐标
  2. 添加 marker
  3. 绘制 polygon
javascript
// 地图点击事件
async clickMapHandler(e) {
    console.log(e,'---点击事件')
    ...
    // 添加 marker
    this.addMarker();
    // 绘制 polygon,三点成形
    if(this.isAddPolygon && this.polygonPath.length >= 3) {
        this.setPolygon()
    }
},

添加点标记 (marker)

javascript
// 添加点标记
addMarker() {
    // 定义 点标记
    let marker = new AMap.Marker({
        position: new AMap.LngLat(this.location.lng, this.location.lat), // 点标记的经纬度位置
    });
    // 往点标记数组中 push
    this.markerList.push(marker);
    if(this.isAddPolygon) {
        // 往polygon数组中 push
        this.polygonPath.push(new AMap.LngLat(this.location.lng, this.location.lat));
    }
    // 在地图上添加点标记
    map.add(marker);
},

绘制多边形 (polygon)

javascript
// 绘制多边形
setPolygon() {
    // 每当 polygon 路径长度大于 3 时,销毁 polygon(也就是重新绘制,覆盖原先的)
    if(this.polygonPath.length > 3) {
        this.polygon.destroy();
    }
    // polygon 实例化
    this.polygon = new AMap.Polygon({
        path: this.polygonPath, //路径
        fillColor: "#fff", //多边形填充颜色
        strokeWeight: 2, //线条宽度,默认为 2
        strokeColor: "red", //线条颜色
    });
    console.log(this.polygon,'----polygon')
    // 在地图上添加 polygon
    map.add(this.polygon);
},

清除所有点标记

javascript
// 清空所有点标记
clearMarkers() {
    // 销毁多边形
    if(this.isAddPolygon) {
        this.polygonPath = [];
        this.polygon.destroy();
    }
    // 地图上移出所有点标记
    map.remove(this.markerList);
},