Mapbox Maps iOS自定义3D Pucker无法绑定用户当前位置如何解决?
问题原因
你在创建Model实例时硬编码了固定的经纬度坐标,该参数会覆盖Mapbox Puck组件默认的实时位置绑定逻辑,导致3D模型固定在指定坐标不会更新。
解决方案
仅需删除Model初始化时的position参数即可,Mapbox的3D Puck组件会自动将模型与系统返回的用户实时位置绑定,无需手动同步位置:
// 原错误代码 // let myModel = Model(uri: uri, position: [-77.150925, 39.085006], orientation: [0, 0, 180]) // 修改后代码 let myModel = Model(uri: uri, orientation: [0, 0, 180])
如果需要让3D模型随用户移动方向自动调整朝向,可以在初始化Puck3DConfiguration时添加modelRotation配置:
let configuration = Puck3DConfiguration( model: myModel, modelScale: .expression(scalingExpression), // 绑定用户移动方向,自动调整模型朝向 modelRotation: .expression(Exp(.get) { "bearing" }) )
修改后完整代码
// ViewController.swift import UIKit import MapboxMaps public class ViewController: UIViewController { internal var mapView: MapView! internal var cameraLocationConsumer: CameraLocationConsumer! override public func viewDidLoad() { super.viewDidLoad() let options = MapInitOptions(cameraOptions: CameraOptions(zoom: 16)) mapView = MapView(frame: view.bounds, mapInitOptions: options) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(mapView) mapView.mapboxMap.onNext(.styleLoaded) { _ in self.loadCharacter() } cameraLocationConsumer = CameraLocationConsumer(mapView: mapView) mapView.mapboxMap.onNext(.mapLoaded) { _ in self.mapView.location.addLocationConsumer(newConsumer: self.cameraLocationConsumer) } } internal func loadCharacter() { let uri = Bundle.main.url(forResource: "race_car_model", withExtension: "gltf") // 移除硬编码的position参数,Puck自动绑定实时位置 let myModel = Model(uri: uri, orientation: [0, 0, 180]) let scalingExpression = Exp(.interpolate) { Exp(.linear) Exp(.zoom) 0 Exp(.literal) { [256000.0, 256000.0, 256000.0] } 4 Exp(.literal) { [40000.0, 40000.0, 40000.0] } 8 Exp(.literal) { [2000.0, 2000.0, 2000.0] } 12 Exp(.literal) { [100.0, 100.0, 100.0] } 16 Exp(.literal) { [7.0, 7.0, 7.0] } 20 Exp(.literal) { [1.0, 1.0, 1.0] } } let configuration = Puck3DConfiguration( model: myModel, modelScale: .expression(scalingExpression), modelRotation: .expression(Exp(.get) { "bearing" }) ) mapView.location.options.puckType = .puck3D(configuration) } } public class CameraLocationConsumer: LocationConsumer { weak var mapView: MapView? init(mapView: MapView) { self.mapView = mapView } public func locationUpdate(newLocation: Location) { mapView?.camera.ease( to: CameraOptions(center: newLocation.coordinate, zoom: 16, pitch: 50.0), duration: 1.3 ) } }
内容的提问来源于stack exchange,提问作者safnasfsa
相关产品推荐
相关产品推荐

