使用Vue Baidu Map对百度地图实现输入框搜索定位
前端时间需要在页面的输入框输入地址,搜索并在百度地图上获取选定结果的坐标,前端使用了Vue + Element-ui,地图方面直接使用了封装好的百度地图vue组件-vue-baidu-map
输入框使用自动完成的Input组件,在输入地址时不断更新地图搜索结果和地图当前定位。
以下是demo代码
<template> <div class="app-container"> <el-autocomplete v-model="mapLocation.address" :fetch-suggestions="querySearch" placeholder="请输入详细地址" style="width: 100%" :trigger-on-focus="false" @select="handleSelect" /> <div style="margin: 5px"> <baidu-map class="bm-view" :center="mapCenter" :zoom="mapZoom" :scroll-wheel-zoom="true" ak="baidu-ak" @ready="handlerBMap" /> </div> </div> </template> <script> import BaiduMap from 'vue-baidu-map/components/map/Map.vue' export default { name: 'BaiduMapDemo', components: { BaiduMap }, data() { return { mapZoom: 15, mapCenter: { lng: 0, lat: 0 }, mapLocation: { address: undefined, coordinate: undefined } } }, methods: { handlerBMap({ BMap, map }) { this.BMap = BMap this.map = map if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) { this.mapCenter.lng = this.mapLocation.coordinate.lng this.mapCenter.lat = this.mapLocation.coordinate.lat this.mapZoom = 15 map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate)) } else { this.mapCenter.lng = 113.271429 this.mapCenter.lat = 23.135336 this.mapZoom = 10 } }, querySearch(queryString, cb) { var that = this var myGeo = new this.BMap.Geocoder() myGeo.getPoint(queryString, function(point) { if (point) { that.mapLocation.coordinate = point that.makerCenter(point) } else { that.mapLocation.coordinate = null } }, this.locationCity) var options = { onSearchComplete: function(results) { if (local.getStatus() === 0) { // 判断状态是否正确 var s = [] for (var i = 0; i < results.getCurrentNumPois(); i++) { var x = results.getPoi(i) var item = { value: x.address + x.title, point: x.point } s.push(item) cb(s) } } else { cb() } } } var local = new this.BMap.LocalSearch(this.map, options) local.search(queryString) }, handleSelect(item) { var { point } = item this.mapLocation.coordinate = point this.makerCenter(point) }, makerCenter(point) { if (this.map) { this.map.clearOverlays() this.map.addOverlay(new this.BMap.Marker(point)) this.mapCenter.lng = point.lng this.mapCenter.lat = point.lat this.mapZoom = 15 } } } } </script> <style> .bm-view { width: 100%; height: 500px; } </style>
效果图
分类:
Vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述