移動端定位

項目中用到了自動定位獲取當前的位置的功能,引入高德地圖中的定位和使用微信JS-SDK中的定位功能,具體代碼以下:javascript

h5定位:

  • 首先安裝高德插件AMap
  • 在項目中(咱們使用的是vue框架)create生命週期方法中加載高德地圖初始化方法(代碼以下)
created() {
    VueAMap.initAMapApiLoader({
      // 高德的key
      key: '本身申請的ID',
      // 插件集合
      plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.Geocoder', 'AMap.Geolocation'],
      // 高德 sdk 版本,默認爲 1.4.4
      v: '1.4.4'
    })
  },

複製代碼
  • 執行獲取當前地址的方法(此方法是異步方法,因此點擊獲取地址功能按鈕時,會有幾秒的延時,親測會有3s-10s的時間),返回值是經緯度
var map = new AMap.Map('container', {
          resizeEnable: true
        })
        const self = this
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位,默認:true
            timeout: 5000, // 超過10秒後中止定位,默認:5s
            buttonPosition: 'RB', // 定位按鈕的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), // 定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
            zoomToAccuracy: true // 定位成功後是否自動調整地圖視野到定位點
          })
          geolocation.getCurrentPosition((status, result) => {
            console.log(status, result)

複製代碼
  • 獲取到經緯度,根據經緯度轉化爲具體地址(地址的精確性存在問題,可是能夠定位到大概位置)
if (result && result.position) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([result.position.lng, result.position.lat], function(status, result) {
                  if (status === 'complete' && result.info === 'OK') {
                    self.isLoading = false
                    self.data ={
                      ...self.data,
                      province: result.regeocode.addressComponent.province, 
                      city: result.regeocode.addressComponent.city,
                      county: result.regeocode.addressComponent.district,
                      area_code: result.regeocode.addressComponent.adcode
                    }
                  }
                })
              })

複製代碼

微信定位

  • 首先判斷是否在微信環境中而後執行以下代碼
wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            if (res.longitude && res.latitude) {
              AMap.plugin('AMap.Geocoder', function() {
                var geocoder = new AMap.Geocoder({
                  city: '010'
                })
                geocoder.getAddress([res.longitude, res.latitude], function(status, result) {


複製代碼

返回的longitude和latitude就是經緯度,而後調用高德地圖經緯度轉化爲具體的方法。vue

第一次寫,沒有經驗。但願能夠你們不吝賜教,謝謝!java

相關文章
相關標籤/搜索