Uni App 地图调用:如何使用 Google Maps API 查找附近地点
首先,需要安装 vue-cli 和相关的依赖:
npm install -g vue-cli
npm install vue-router --save
npm install axios --save
然后,创建一个新的 Vue 项目:
vue init webpack my-project
cd my-project
npm install
接下来,安装地图相关的依赖:
npm install vue2-google-maps --save
在 main.js 文件中引入 vue2-google-maps 和 axios:
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import * as VueGoogleMaps from 'vue2-google-maps'
Vue.use(VueRouter)
Vue.prototype.$http = axios
Vue.use(VueGoogleMaps, {
load: {
key: 'YOUR_GOOGLE_MAPS_API_KEY',
libraries: 'places',
},
})
在 App.vue 文件中添加地图组件:
<template>
<div>
<h1>Find Nearby Places</h1>
<GmapMap
:center='{lat: 37.7749, lng: -122.4194}'
:zoom='12'
@click='addMarker'
>
<GmapMarker
v-for='(m, index) in markers'
:key='index'
:position='m.position'
:clickable='true'
@click='removeMarker(index)'
/>
</GmapMap>
</div>
</template>
<script>
export default {
data() {
return {
markers: [],
}
},
methods: {
addMarker(e) {
this.markers.push({
position: e.latLng,
})
},
removeMarker(index) {
this.markers.splice(index, 1)
},
},
}
</script>
这里使用了 vue2-google-maps 组件库来生成地图,并添加了一个点击事件来添加标记。接下来,需要使用 Google Places API 来搜索附近的地点。
在 App.vue 文件中添加一个搜索框和一个搜索按钮:
<template>
<div>
<h1>Find Nearby Places</h1>
<GmapMap
:center='{lat: 37.7749, lng: -122.4194}'
:zoom='12'
@click='addMarker'
>
<GmapMarker
v-for='(m, index) in markers'
:key='index'
:position='m.position'
:clickable='true'
@click='removeMarker(index)'
/>
</GmapMap>
<div>
<input type='text' v-model='searchTerm' />
<button @click='search'>Search</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
markers: [],
searchTerm: '',
}
},
methods: {
addMarker(e) {
this.markers.push({
position: e.latLng,
})
},
removeMarker(index) {
this.markers.splice(index, 1)
},
search() {
const service = new google.maps.places.PlacesService(
this.$refs.map.$mapObject
)
service.textSearch(
{
query: this.searchTerm,
location: { lat: 37.7749, lng: -122.4194 },
radius: 5000,
},
(results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (let i = 0; i < results.length; i++) {
this.markers.push({
position: results[i].geometry.location,
})
}
}
}
)
},
},
}
</script>
这里使用了 Google Places API 的 textSearch 方法来搜索附近的地点,并将结果添加到地图上。需要注意的是,需要在 Google Cloud Console 中启用 Places API,并获取 API 密钥。
最后,可以运行应用程序并测试它是否工作正常:
npm run dev
原文地址: https://www.cveoy.top/t/topic/hglu 著作权归作者所有。请勿转载和采集!