Vue 高德地图实现添加标记,AMap.PlaceSearch 地点搜索,根据页面主题修改地图样式

Vue 高德地图实现添加标记,AMap.PlaceSearch 地点搜索,根据页面主题修改地图样式

效果图 


成为开发者并创建key

详细请查阅官方文档:https://developer.amap.com/api/jsapi-v2/guide/abc/prepare


一、引入文件,详细请查阅官方文档

<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>

二、定义变量

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

三、地图、地点搜索HTML及样式

// 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;
}

四、地图实例化,并根据系统主题设置地图样式

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

五、AMap.ToolBar(工具条)、AMap.PlaceSearch(地点搜索) 插件的使用

/*
* @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]);
    }
},

六、点击地图添加标记

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);
}

七、获取页面主题信息,并监听

/*
* @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'}`)
    })
}

如果有错误,麻烦指出~

  • 11
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
如果在Vue项目中使用高德地图时遇到了“AMap.Driving is not a constructor”错误,这可能是因为您未正确引入Driving插件或引入方式不正确。 在Vue项目中使用高德地图,可以通过在main.js文件中引入高德地图API并注册为全局变量来实现全局使用。例如: ```javascript // main.js import Vue from 'vue' import App from './App.vue' // 引入高德地图API import AMap from 'AMap' Vue.config.productionTip = false // 注册高德地图API为全局变量 Vue.prototype.AMap = AMap new Vue({ render: h => h(App), }).$mount('#app') ``` 在上面的代码中,我们引入了高德地图API,并通过Vue.prototype将其注册为Vue的全局变量,使其在所有组件中可用。 然后,您可以在Vue组件中使用AMap对象和Driving类来计算路线并绘制路径。例如: ```javascript <template> <div id="mapContainer" style="height:500px"></div> </template> <script> export default { data() { return { map: null, driving: null } }, mounted() { // 初始化地图 this.map = new this.AMap.Map('mapContainer', { center: [116.397428, 39.90923], zoom: 13 }); // 创建Driving对象 this.driving = new this.AMap.Driving({ map: this.map, panel: 'panel' }); // 计算路线 var points = [ [116.379028, 39.865042], [116.414032, 39.865042], [116.414032, 39.899042], [116.379028, 39.899042] ]; this.driving.search(points, (status, result) => { if (status === 'complete' && result.info === 'OK') { // 获取路线经纬度坐标数组 var path = result.routes[0].path; // 创建Polyline对象绘制路径曲线 var polyline = new this.AMap.Polyline({ path: path, strokeColor: '#3366FF', strokeWeight: 5, strokeOpacity: 0.8 }); polyline.setMap(this.map); } else { alert('路线计算失败'); } }); } } </script> ``` 在上面的代码中,我们在Vue组件的mounted生命周期函数中创建了地图和Driving对象,并计算了路线。请注意,我们使用Vue.prototype.AMap和this.AMap来访问全局的AMap对象,并使用this.AMap.Driving来访问Driving类。这样,您就可以在Vue项目中使用高德地图API,而不必担心“AMap.Driving is not a constructor”错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忍冬 ⁡⁡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值