vue实现搜索附近医院
实现思路
通过Vue结合高德地图API或百度地图API实现搜索附近医院功能。核心步骤包括获取用户位置、调用地图API搜索附近医院、展示结果。
获取用户位置
使用浏览器Geolocation API获取用户经纬度坐标。需注意https环境下才能正常调用。
navigator.geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords
this.userLocation = { lat: latitude, lng: longitude }
},
error => {
console.error('获取位置失败:', error)
}
)
调用地图API
以高德地图为例,需先引入AMap SDK:
<script src="https://webapi.amap.com/maps?v=2.0&key=你的高德Key"></script>
创建地图实例并搜索:
const map = new AMap.Map('map-container', {
center: [this.userLocation.lng, this.userLocation.lat],
zoom: 15
})
AMap.plugin('AMap.PlaceSearch', () => {
const placeSearch = new AMap.PlaceSearch({
type: '医院',
pageSize: 20
})
placeSearch.searchNearBy('', [this.userLocation.lng, this.userLocation.lat], 5000, (status, result) => {
this.hospitals = result.poiList.pois
})
})
展示搜索结果
在Vue模板中渲染医院列表:
<div v-for="hospital in hospitals" :key="hospital.id">
<h3>{{ hospital.name }}</h3>
<p>{{ hospital.address }}</p>
<p>距离:{{ hospital.distance }}米</p>
<p>电话:{{ hospital.tel || '暂无' }}</p>
</div>
完整组件示例
<template>
<div>
<div id="map-container" style="width:100%;height:300px"></div>
<div v-if="hospitals.length">
<div v-for="hospital in hospitals" :key="hospital.id">
<h3>{{ hospital.name }}</h3>
<p>{{ hospital.address }}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
userLocation: null,
hospitals: []
}
},
mounted() {
this.initMap()
},
methods: {
initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.userLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
this.loadAMap()
},
error => {
console.error('获取位置失败:', error)
}
)
}
},
loadAMap() {
const script = document.createElement('script')
script.src = `https://webapi.amap.com/maps?v=2.0&key=你的高德Key`
script.onload = () => this.searchHospitals()
document.head.appendChild(script)
},
searchHospitals() {
const map = new AMap.Map('map-container', {
center: [this.userLocation.lng, this.userLocation.lat],
zoom: 15
})
AMap.plugin('AMap.PlaceSearch', () => {
const placeSearch = new AMap.PlaceSearch({
type: '医院',
pageSize: 20
})
placeSearch.searchNearBy('', [this.userLocation.lng, this.userLocation.lat], 5000, (status, result) => {
this.hospitals = result.poiList.pois
})
})
}
}
}
</script>
注意事项
- 需申请高德或百度地图开发者Key
- 生产环境需处理定位失败等异常情况
- 可添加距离排序、分类筛选等增强功能
- 移动端建议添加定位权限请求提示





