vue 高德地图点击城市列表定位
时间: 2023-07-06 10:19:24 浏览: 181
要实现在 Vue 中点击城市列表定位到对应的地图位置,可以遵循以下步骤:
1. 在 Vue 组件中引入高德地图 JavaScript API,并创建地图实例。
2. 在组件中设置一个城市列表,可以是一个数组,每个元素包含城市名称和经纬度信息。
3. 在模板中渲染城市列表,并为每个城市名称设置一个点击事件。
4. 在点击事件中获取被点击的城市名称,并根据名称查找对应的经纬度信息。
5. 使用地图实例的 setCenter 方法将地图中心设置为对应的经纬度。
以下是一个示例代码,假设城市列表为一个数组 cities,每个元素包含 name 和 location 两个属性:
```
<template>
<div>
<ul>
<li v-for="city in cities" :key="city.name" @click="goToCity(city.name)">{{ city.name }}</li>
</ul>
<div id="map" style="width: 100%; height: 500px;"></div>
</div>
</template>
<script>
import { Map } from 'AMap'
export default {
data() {
return {
map: null,
cities: [
{ name: '北京', location: [116.397428, 39.90923] },
{ name: '上海', location: [121.472641, 31.231707] },
{ name: '广州', location: [113.264434, 23.129162] }
]
}
},
mounted() {
this.map = new Map('map', {
center: this.cities[0].location,
zoom: 13
})
},
methods: {
goToCity(cityName) {
const city = this.cities.find(c => c.name === cityName)
if (city) {
this.map.setCenter(city.location)
}
}
}
}
</script>
```
在这个示例中,我们将地图实例保存在组件的 data 中,使用 AMap.Map 创建地图,并在 mounted 生命周期中初始化地图。在模板中渲染城市列表,并为每个城市名称设置了一个点击事件。在 goToCity 方法中,根据城市名称查找对应的经纬度信息,然后使用 setCenter 方法将地图中心设置为该位置。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)