Appearance
定位
Location 用户定位
功能说明
SFMapView 内置用户定位功能,通过 showsUserLocation 控制定位小蓝点的显隐。支持两种跟踪模式(不跟随/跟随),可通过 SFMUserLocationRepresentation 自定义定位图标样式。位置更新和模式变化通过 delegate 回调通知。
关键代码
objc
// ── 显示/隐藏定位 ──
self.mapView.showsUserLocation = YES; // 显示小蓝点
self.mapView.showsUserLocation = NO; // 隐藏
// ── 跟踪模式 ──
[self.mapView setUserTrackingMode:SFMUserTrackingModeNone animated:YES]; // 不跟随
[self.mapView setUserTrackingMode:SFMUserTrackingModeFollow animated:YES]; // 跟随(地图中心跟随用户)
// ── 蓝色脉冲样式(默认)──
SFMUserLocationRepresentation *r = [SFMUserLocationRepresentation new];
r.showsAccuracyRing = YES; // 显示精度圈
r.enablePulseAnnimation = YES; // 启用脉冲动画
r.image = nil; // nil = 使用默认蓝色小蓝点
[self.mapView updateUserLocationRepresentation:r];
// ── 自定义图标样式 ──
SFMUserLocationRepresentation *r = [SFMUserLocationRepresentation new];
r.showsAccuracyRing = NO;
r.enablePulseAnnimation = NO;
r.image = customImage; // 自定义定位图标
[self.mapView updateUserLocationRepresentation:r];
// ── delegate: 位置更新回调 ──
- (void)mapView:(SFMapView *)mapView
didUpdateUserLocation:(SFMUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation {
if (updatingLocation && userLocation.location != nil) {
CLLocationCoordinate2D coord = userLocation.location.coordinate;
// coord.latitude / coord.longitude
}
}
// ── delegate: 跟踪模式变化回调 ──
- (void)mapView:(SFMapView *)mapView
didChangeUserTrackingMode:(SFMUserTrackingMode)mode
animated:(BOOL)animated {
// mode: SFMUserTrackingModeNone / Follow
}
// ── delegate: 定位失败回调 ──
- (void)mapView:(SFMapView *)mapView
didFailToLocateUserWithError:(NSError *)error {
// error.localizedDescription
}要点 / 注意事项
showsUserLocation = YES后 SDK 会自动请求系统定位权限,需在Info.plist中配置NSLocationWhenInUseUsageDescription。- 两种跟踪模式:
None(不跟随,可自由拖动地图)、Follow(地图中心始终跟随用户位置)。 SFMUserLocationRepresentation用于自定义定位图标:showsAccuracyRing控制精度圈显隐,enablePulseAnnimation控制脉冲动画,image设为 nil 使用默认蓝色小蓝点。didUpdateUserLocation:updatingLocation:回调中userLocation.location是CLLocation对象,包含坐标、速度、朝向等信息。- 定位失败时通过
didFailToLocateUserWithError:回调,常见原因为权限未授予或定位服务关闭。
