HWLocationUtils.ets 5.56 KB
import { Logger } from './Logger';
import { PermissionUtils } from './PermissionUtils';
import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
import { SPHelper } from './SPHelper';

/**
 * 系统定位服务实现
 * */
export class HWLocationUtils {
  //d定位相关
  static LOCATION_CITY_NAME = "location_city_name" //定位
  static LOCATION_CITY_CODE = "location_city_code" //定位


  static LOCATION: Permissions = 'ohos.permission.LOCATION'
  static APPROXIMATELY_LOCATION: Permissions = 'ohos.permission.APPROXIMATELY_LOCATION'

  private static getLocation() {
    let requestInfo: geoLocationManager.LocationRequest = {
      'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
      'scenario': geoLocationManager.LocationRequestScenario.UNSET,
      distanceInterval: 0,
      timeInterval: 60,
      maxAccuracy: 0
    };
    geoLocationManager.on('locationChange', requestInfo, (data) => {
      Logger.debug('location :' + JSON.stringify(data))
    })
  }

  private static getLocationData() {
    return new Promise<Record<string, string | number>>((success, fail) => {
      let requestInfo: geoLocationManager.LocationRequest = {
        'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
        'scenario': geoLocationManager.LocationRequestScenario.DAILY_LIFE_SERVICE,
        distanceInterval: 0,
        timeInterval: 60,
        maxAccuracy: 0
      };
      geoLocationManager.on('locationChange', requestInfo, (data) => {
        Logger.debug('location :' + JSON.stringify(data)) //{"latitude":31.86870096,"longitude":117.3015341,"altitude":0,"accuracy":5000,"speed":0,"timeStamp":1713332445643,"direction":0,"timeSinceBoot":589519570869240,"additions":"","additionSize":0}
        let record: Record<string, string | number> = {};
        record['latitude'] = data.latitude
        record['longitude'] = data.longitude
        success(record)
      })
    })
  }

  //开启定位服务
  static async startLocationService() {
    let grant = await PermissionUtils.checkPermissions(HWLocationUtils.APPROXIMATELY_LOCATION)
    if (grant) {
      HWLocationUtils.getCurrentLocation()
      return
    }
    let context = getContext();
    let requestGrant = await PermissionUtils.reqPermissionsFromUser([HWLocationUtils.APPROXIMATELY_LOCATION], context);
    Logger.debug('location2 :' + requestGrant)
    if (requestGrant) {
      HWLocationUtils.getCurrentLocation()
    } else {
      PermissionUtils.openPermissionsInSystemSettings(context)
    }
  }

  private static getCurrentLocation() {
    let requestInfo: geoLocationManager.CurrentLocationRequest = {
      'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
      'scenario': geoLocationManager.LocationRequestScenario.DAILY_LIFE_SERVICE,
      'maxAccuracy': 0
    };
    try {
      geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
        //{"latitude":31.8687047,"longitude":117.30152005,"altitude":0,"accuracy":5000,"speed":0,"timeStamp":1713331875766,"direction":0,"timeSinceBoot":588949694096931,"additions":"","additionSize":0}
        Logger.debug('location' + JSON.stringify(result))
        HWLocationUtils.getReverseGeoCodeRequest(result.latitude, result.longitude)
      })
        .catch((error: number) => {
          Logger.debug('location' + JSON.stringify(error))
        });
    } catch (err) {
    }
  }

  private static getGeoCodeRequest(description: string) {
    let requestInfo: geoLocationManager.GeoCodeRequest = { 'description': description };
    geoLocationManager.getAddressesFromLocationName(requestInfo, (error, data) => {
      if (data) {
        Logger.debug('location :' + JSON.stringify(data))
      }
      //[{"latitude":31.898204927828598,"longitude":117.29702564819466,"locale":"zh","placeName":"安徽省合肥市瑶海区白龙路与北二环路辅路交叉口南20米","countryCode":"CN","countryName":"中国","administrativeArea":"安徽省","subAdministrativeArea":"合肥市","locality":"合肥市","subLocality":"瑶海区","roadName":"白龙路与北二环路辅路","subRoadName":"20","premises":"20","postalCode":"","phoneNumber":"18756071597","addressUrl":"","descriptionsSize":0,"isFromMock":false}]
    })
  }

  private static getReverseGeoCodeRequest(latitude: number, longitude: number) {
    let requestInfo: geoLocationManager.ReverseGeoCodeRequest = {
      "latitude": latitude,
      "longitude": longitude,
      "maxItems": 2
    };
    geoLocationManager.getAddressesFromLocation(requestInfo, (error, data) => {
      if (error) {
        Logger.debug('location :' + JSON.stringify(error))
      }
      if (data) {
        Logger.debug('location :' + JSON.stringify(data))
        if (data[0] && data[0].countryName) {
          if (data[0].descriptionsSize && data[0].descriptions) {
            let code = data[0].descriptions[1]
            let cityCode = code.substring(0, 6)
            let cityName = data[0].subAdministrativeArea;
            if (cityName) {
              SPHelper.default.save(HWLocationUtils.LOCATION_CITY_NAME, cityName)
            }
            if (cityCode) {
              SPHelper.default.save(HWLocationUtils.LOCATION_CITY_NAME, cityCode)
            }
          }
        }
      }
    })
  }


  //取消定位
  static cancelLocation() {
    // geoLocationManager.off('locationChange')
    return new Promise<boolean>((success, fail) => {
      geoLocationManager.off("locationChange", (data) => {
        Logger.debug('location :' + JSON.stringify(data))
        success(true)
      })
    })
  }
}