[TOC]
#### Vue 利用高德定位實現餓了么定位當前位置

1. 注冊高德開發者 https://lbs.amap.com
2. 創建一個應用,拿到key

3. 獲取JS代碼

4. public / index.html 引入代碼
>[danger] 注意,一定要在頭部引入

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. 如何使用
在需要使用定位的組件中寫入以下代碼:


- 起步
- 環境搭建
- mock數據
- 基礎
- 生命周期
- 過濾器
- 過渡動畫
- keyframes動畫
- 動畫JS鉤子
- 路由
- 導航守衛
- 全局守衛
- 監聽器
- 自定義組件
- 獲取焦點
- mixins
- mixins抽離vuex
- 國際化
- 動態組件
- Dom
- 擴展
- 安裝devTools
- scss
- Nuxt引用多個UI庫
- vuex
- vuex命名空間
- vuex定義
- cli
- 安裝與卸載
- 環境變量
- 雜項
- Mock數據
- FeHelper
- git
- 反向代理
- 本地存儲
- stylus
- 常用mixins
- jsonp
- 配置
- mock配置
- 跨域配置
- 自定義路徑
- px2rem
- 代理后端請求
- 常用算法
- 字母排序城市數據
- 倒計時
- 通訊錄數據結構
- 請求
- axios防止多次請求
- 封裝axios請求
- axios使用
- 封裝axios
- 插件
- BetterScroll
- 高德定位
- polyfill
- fastClick
- LazyLoad
- storageCache
- moment
- keyFrameAnimation
- vueSwiper
- 組件
- Loading組件
- header組件
- 仿有道App導航
- SupportIcon
- 仿餓了么購物車跳動
- 購物車小球緩動
- 小球飛入購物車
- 仿音樂歌手列表
- 唱片飛入效果
- 搜索組件
- 仿美團PC搜索框
- 頁面布局
- stickyFooter
- 背景色漸變
- 背景虛化
- Ui組件
- CubeUi
- CreateApi
- tab滑屏切換
- 索引列表
- BScroll
- BScroll左右聯動導航
- vant
- 函數庫
- 常用Dom函數庫
- axios封裝
- 格式化音樂播放時長
- 搜索節流
- time格式化
- JS基礎
- window對象中的高度
- JS中的寬高
- 常用正則
- nuxt
- nuxtVuex
- 監聽頁面滾動
- 監聽body滾動
- 監聽局部滾動