04- 使用腾讯地图

171 阅读1分钟

一、使用腾讯地图

第一步:申请腾讯地图账号

lbs.qq.com/miniProgram…

第二步:申请对应的账号

![image-20221121202731309](/Users/jirongliang/Library/Application Support/typora-user-images/image-20221121202731309.png)

第三步、混合配置weixin对应的接口

/* 小程序特有相关 */
  "mp-weixin": {
    "appid": "wx73336bd20a9c9633",
    "setting": {
      "urlCheck": false
    },
    "usingComponents": true,
    // 位置相关配置
		"permission": {
			"scope.userLocation": {
				"desc": "获取当前位置"
			}
		},
    // 需要用到的接口API
		"requiredPrivateInfos": ["startLocationUpdate", "onLocationChange"]
  },

第四步、封装获取当前位置的方法

export function getLocation(): Promise<Pres> {
  return new Promise((resolve, reject) => {
    uni.startLocationUpdate({
      success: (res) => {
        uni.onLocationChange(async (add: { latitude: number; longitude: number }) => {
          // latitude  获取纬度
          // longitude 获取经度
          uni.stopLocationUpdate() //关闭监听实时位置变化,前后台都停止消息接收
          const address = await addRess(add.latitude, add.longitude)
          resolve(address)
        })
      },
      fail: (err) => {
        resolve({
          code: 202,
          msg: '北京市 东城区 开启定位',
          city: 'none',
          province: 'none',
          lat: 'none',
          lng: 'none'
        })
      }
    })
  })
}

// 获取位置
interface Adddress {
  message: string
  status: number
  result: {
    address_component: { city: string; province: string; district: string }
    location: { lat: number; lng: number }
    address: string
  }
}
function addRess(latitude: number, longitude: number): Promise<Pres> {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      location: { latitude, longitude },
      success: (res: Adddress) => {
        // 获取详细位置信息
        uni.setStorageSync('address', {
          address: res.result.address,
          location: res.result.location
        })
        if (res.message == 'query ok' && res.status == 0) {
          resolve({
            code: 200,
            msg: 'success',
            city: res.result.address_component.city,
            province: res.result.address_component.province,
            district: res.result.address_component.district,
            lat: res.result.location.lat,
            lng: res.result.location.lng
          })
        } else {
          throw {
            code: 202,
            msg: '定位失败,程序出现bug',
            city: 'none',
            province: 'none',
            lat: 'none',
            lng: 'none'
          }
        }
      },
      fail: (err: any) => {
        resolve({
          code: 202,
          msg: '定位失败,程序出现bug',
          city: 'none',
          province: 'none',
          lat: 'none',
          lng: 'none'
        })
      }
    })
  })
}