Vue 高德地图模糊地址搜索:由近到远查询
在 Vue 中使用高德地图进行输入模糊查询,查询地址由进到远,可以按照以下步骤进行:
- 在项目中安装高德地图的 JavaScript API 库。可以通过 npm 或 yarn 安装,命令如下:
npm install @amap/amap-jsapi-loader --save
- 在需要使用地图的组件中引入高德地图的 JavaScript API 库:
import { AMapLoader } from '@amap/amap-jsapi-loader';
export default {
name: 'MapComponent',
data() {
return {
map: null,
input: '',
results: []
};
},
mounted() {
AMapLoader.load({
key: 'YOUR_AMAP_API_KEY',
version: '2.0',
plugins: ['AMap.PlaceSearch']
}).then(() => {
this.initMap();
});
},
methods: {
initMap() {
this.map = new AMap.Map('map-container', {
zoom: 14
});
},
searchAddress() {
if (this.input) {
const placeSearch = new AMap.PlaceSearch({
city: '全国'
});
placeSearch.search(this.input, (status, result) => {
if (status === 'complete' && result.info === 'OK') {
this.results = result.poiList.pois;
}
});
}
}
}
}
- 在模板中添加输入框和地图容器:
<template>
<div>
<input v-model='input' @input='searchAddress' placeholder='请输入地址'>
<div id='map-container'></div>
<ul>
<li v-for='result in results' :key='result.id'>
{{ result.name }}
</li>
</ul>
</div>
</template>
在上面的代码中,首先在mounted钩子函数中加载高德地图的 JavaScript API 库,并在加载完成后调用initMap方法初始化地图。然后,在输入框的input事件中调用searchAddress方法进行地址模糊查询,并将查询结果保存在results数组中,在模板中使用v-for指令遍历显示查询结果。
需要注意的是,上述代码中的YOUR_AMAP_API_KEY需要替换为你自己的高德地图 API 密钥。同时,根据实际需求,还可以根据高德地图 API 文档中的参数配置,对地图的显示和查询进行更多的定制。
原文地址: https://www.cveoy.top/t/topic/qsrK 著作权归作者所有。请勿转载和采集!