企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] #### Vue 利用高德定位实现饿了么定位当前位置 ![](https://box.kancloud.cn/f1b8d5a28c12f06941a36c54afea7415_376x382.png) 1. 注册高德开发者 https://lbs.amap.com 2. 创建一个应用,拿到key ![](https://box.kancloud.cn/d33ae75346edb52b8e0106dd6ac07645_728x576.png) 3. 获取JS代码 ![](https://box.kancloud.cn/4f8eba35d14d91f035da3b655670825c_563x261.png) 4. public / index.html 引入代码 >[danger] 注意,一定要在头部引入 ![](https://box.kancloud.cn/f9af25d283f6893b5cf475027c8bb83b_681x356.png) 5. App.vue 中加入以下代码 ~~~ <template> <div id="app"> <router-view /> </div> </template> <script> import { createNamespacedHelpers } from 'vuex' const { mapActions } = createNamespacedHelpers('city'); export default { name: 'app', created() { this.getLocation() }, methods: { ...mapActions([ 'setlocation', 'setcity' ]), getLocation() { const self = this; AMap.plugin('AMap.Geolocation', function() { var geolocation = new AMap.Geolocation({ // 是否使用高精度定位,默认:true enableHighAccuracy: true, // 设置定位超时时间,默认:无穷大 timeout: 10000 }) geolocation.getCurrentPosition() AMap.event.addListener(geolocation, 'complete', onComplete) AMap.event.addListener(geolocation, 'error', onError) function onComplete (data) { // data是具体的定位信息 // 存入vuex中 self.setlocation(data) self.setcity(data.formattedAddress) } function onError (data) { // 定位出错 self.getLngLatLocation() } }) }, getLngLatLocation() { const self = this; AMap.plugin('AMap.CitySearch', function () { var citySearch = new AMap.CitySearch() citySearch.getLocalCity(function (status, result) { if (status === 'complete' && result.info === 'OK') { // 查询成功,result即为当前所在城市信息 AMap.plugin('AMap.Geocoder', function() { var geocoder = new AMap.Geocoder({ // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode city: result.adcode }) var lnglat = result.rectangle.split(";")[0].split(","); geocoder.getAddress(lnglat, function(status, data) { if (status === 'complete' && data.info === 'OK') { // result为对应的地理位置详细信息 // 存入 vuex 中 self.setlocation({ addressComponent: { city: result.city, province: result.province }, formattedAddress: data.regeocode.formattedAddress }); self.setcity(data.regeocode.formattedAddress) } }) }) } }) }) } } } </script> <style lang="stylus"> #app width 100% height 100% overflow hidden background-color: #f5f5f5; </style> ~~~ 6. 如何使用 在需要使用定位的组件中写入以下代码: ![](https://box.kancloud.cn/41fb8bedf6590fdc95dd2e0205478c9f_518x394.png) ![](https://box.kancloud.cn/705d346e6602fb18d723a7df332fa5cc_523x292.png)