Skip to content

CLLocation ​

CLLocation 表示系统量到的一个位置:经纬度、海拔、各个量的误差、速度、移动方向,以及这个位置是什么时候量的。

位置只能由系统给,从 CLLocationManager 得到。它是只读的值:字段不能改,也不能加字段。

要先装 @nacrejs/core-location,装法见 CLLocationManager,也可以看核心和能力包。

继承关系:CLLocation 不继承任何原生类。

构造函数 ​

不能用 new 创建。new CLLocation() 抛 TypeError:

Illegal constructor: a CLLocation comes from CLLocationManager (location, requestLocation(), or the locationupdate event)

位置从这三处得到:

实例属性 ​

所有属性可读、不可写。

属性说明
coordinate 只读经纬度
horizontalAccuracy 只读经纬度的误差半径,米
altitude 只读海拔,相对平均海平面,米
ellipsoidalAltitude 只读海拔,相对 WGS 84 椭球面,米
verticalAccuracy 只读海拔的误差,米
speed 只读移动的速度,米每秒
speedAccuracy 只读速度的误差,米每秒
course 只读移动的方向,度
courseAccuracy 只读方向的误差,度
timestamp 只读这个位置是什么时候量的
sourceInformation 只读这个位置是不是模拟的、是不是来自外接配件

位置里的 null ​

有八个量在系统量不出来时是 null:

是 null 的量说明什么
horizontalAccuracy这个位置的经纬度无效,不要用 coordinate
verticalAccuracy、altitude、ellipsoidalAltitude海拔量不出来。这三个量总是一起是 null,或者一起有值
speed、speedAccuracy速度量不出来
course、courseAccuracy方向量不出来。设备没在移动时就是这样

用这些量之前先判断是不是 null。其余的量(coordinate、timestamp)总是有值。

位置是值 ​

  • 字段不能改,也不能加字段,写了抛 TypeError。改已有的字段,报错是 <字段名> is read-only: locations are values, they cannot be changed。
  • 每次读 manager.location 得到一个新的 CLLocation 对象。比较两个位置是不是同一个,比较它们的字段,不要用 ===。
  • 同一个 CLLocation 上,每次读 coordinate 得到同一个对象。
  • 每次读 timestamp 得到一个新的 Date。修改读出来的 Date 不影响位置。

示例 ​

js
const manager = new CLLocationManager();
manager.requestLocation().then((here) => {
  console.log(here.coordinate.latitude, here.coordinate.longitude);
  if (here.altitude === null) {
    console.log('没有海拔');
  } else {
    console.log('海拔 ' + here.altitude.toFixed(1) + ' 米');
  }
}, (err) => {
  console.log('没取到:' + err.name);
});

效果:取到位置时先输出纬度和经度,再输出海拔(米,保留一位小数)或者「没有海拔」。模拟器里用命令设的位置没有海拔,输出的是「没有海拔」。没有授权时输出 没取到:NotAllowedError。

对应的 iOS API ​

ObjCJS
location.coordinatelocation.coordinate
location.horizontalAccuracy < 0(无效)location.horizontalAccuracy === null
location.speed < 0、location.course < 0(无效)location.speed === null、location.course === null
location.timestamp(NSDate)location.timestamp(Date)
location.sourceInformation.isSimulatedBySoftwarelocation.sourceInformation?.isSimulatedBySoftware

参见 ​