Vue Gaode map implements adding markers, AMap.PlaceSearch place search, and modifying the map style according to the page theme

Vue Gaode map implements adding markers, AMap.PlaceSearch place search, and modifying the map style according to the page theme

renderings 


Become a developer and create a key

For details, please refer to the official document: https://developer.amap.com/api/jsapi-v2/guide/abc/prepare


1. Import documents, please refer to the official documents for details

<script type="text/javascript">
    window._AMapSecurityConfig = {
        serviceHost: `${location.origin}/_AMapService`,
    }
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>

2. Define variables

oAddMapMarker: null, // 添加地图标记实例
oAddMapPlaceSearch: null, // 地图查询服务
sPoiSearch: '', // 地图搜索关键词
aPoiSearchOptions: [], // 可选择地图列表
bPoiSearchLoading: false, // 地图搜索 loading
bThemeNight: false, // 当前页面是否是夜间模式

3. Map, location search HTML and style

// HTML
<div class="g-add-map-marker-dialog-container" ref="addMapMarkerDialogRef"></div>
<div class="g-poi-search">
    <el-select
            v-model="sPoiSearch"
            filterable
            remote
            reserve-keyword
            placeholder="请输入地名"
            :no-data-text="'查询失败,请输入正确地名'"
            :popper-class="'g-poi-search-popper'"
            :remote-method="fnRemoteMethod"
            :loading="bPoiSearchLoading"
            @change="fnPoiSearchChange">
        <el-option
                v-for="item in aPoiSearchOptions"
                :key="item.value"
                :label="item.label"
                :title="item.label"
                :value="item.value">
        </el-option>
    </el-select>
</div>

// CSS
.g-poi-search {
    position: absolute;
    top: 6px;
    right: 6px;
    padding: 8px;
    border-radius: 2px;
    background-color: #fff;
}

.g-poi-search .el-select .el-input > input.el-input__inner {
    height: 28px;
    line-height: 28px;
}

.g-poi-search-popper .el-select-dropdown__item {
    width: 200px;
    height: 28px;
    line-height: 28px;
}

4. Instantiate the map and set the map style according to the system theme

this.oAddMapMarker = new AMap.Map(this.$refs.addMapMarkerDialogRef, {
    zoom: 13, // 级别
    center: [111.51931, 36.088581], // 中心点,没有数据时,可以传null,默认使用当前定位信息
    mapStyle: `amap://styles/${this.bThemeNight ? 'darkblue' : 'normal'}`
})

5. Use of AMap.ToolBar (tool bar), AMap.PlaceSearch (place search) plug-ins

/*
* @desc 异步加载地点搜索服务、工具条插件
* */
fnLoadPlugins() {
    AMap.plugin(['AMap.PlaceSearch', 'AMap.ToolBar'], ()=> {
        this.oAddMapMarker.addControl(new AMap.ToolBar());
        this.oAddMapPlaceSearch = new AMap.PlaceSearch({
            type: "", // 数据类别
            pageSize: 10, // 每页结果数,默认10
            pageIndex: 1, // 请求页码,默认1
            extensions: "base" //返回信息详略,默认为base(基本信息)
        }); //构造PlaceSearch类
        AMap.event.addListener(this.oAddMapPlaceSearch, "complete", (data)=> {
            // 监听地图搜索查询完成
            if(data.info === 'OK' && data.poiList && data.poiList.pois && data.poiList.pois.length) {
                this.aPoiSearchOptions = data.poiList.pois.map(v=> ({
                    value: v.id,
                    label: v.name,
                    location: v.location
                }))
            } else {
                this.aPoiSearchOptions = [];
            }
            this.bPoiSearchLoading = false;
        });
        AMap.event.addListener(this.oAddMapPlaceSearch, "error", (data)=> {
            // 监听地图搜索查询失败
            this.aPoiSearchOptions = [];
            this.bPoiSearchLoading = false;
        });
    });  
},
/*
* @desc 地图远程搜索方法
* @param query {String} 查询字符
* */
fnRemoteMethod(query) {
    if (query !== '' && this.oAddMapPlaceSearch) {
        this.bPoiSearchLoading = true;
        // 根据关键字获取对应城市里相关的POI信息
        this.oAddMapPlaceSearch.search(query);
    } else {
        this.aPoiSearchOptions = [];
    }
},
/*
* @desc 地图搜索关键词发生变化,并添加标记
* param val {String} 当前选中值
* */
fnPoiSearchChange(val) {
    let oFindMap = this.aPoiSearchOptions.find(v=> v.value === val);
    if(oFindMap) {
        // 定位到指定Poi
        this.oAddMapMarker.setCenter([oFindMap.location.lng, oFindMap.location.lat]);
        this.fnAddMapMarkerHandle([oFindMap.location.lng, oFindMap.location.lat]);
    }
},

6. Click on the map to add a marker

this.oAddMapMarker.on('click', (ev)=> {
    this.fnAddMapMarkerHandle([ev.lnglat.lng, ev.lnglat.lat]);
})
/*
* @desc 添加地图标记方法
* @param aLnglat {Array} 经纬度
* */
fnAddMapMarkerHandle(aLnglat) {
    this.oAddMapMarker.getAllOverlays('marker').forEach(marker => {
        // 移除地图中的 marker 覆盖物
        this.oAddMapMarker.remove(marker);
    })
    let oNewMarker = new AMap.Marker({
        position: new AMap.LngLat(aLnglat[0], aLnglat[1]),
        title: '标题title提示',
    });
    // 添加标记
    this.oAddMapMarker.add(oNewMarker);
}

7. Obtain page theme information and monitor

/*
* @desc 获取页面主题,并监听
* */
fnGetPageTheme() {
    let oMatchMedia = window.matchMedia('(prefers-color-scheme: dark)');
    this.bThemeNight = oMatchMedia.matches;
    oMatchMedia.addListener(()=> {
        this.bThemeNight = oMatchMedia.matches;
        if(this.oAddMapMarker) this.oAddMapMarker.setMapStyle(`amap://styles/${this.bThemeNight ? 'darkblue' : 'normal'}`)
    })
}

If there is an error, please point out~

Guess you like

Origin blog.csdn.net/Wang_make/article/details/129900824