Как добавить круговую аннотацию в трепетание MapboxIOS

Программируем под IOS
Ответить
Anonymous
 Как добавить круговую аннотацию в трепетание Mapbox

Сообщение Anonymous »

Я делаю страницу трепетания, и я хочу иметь виджет Mapbox, который показывает выделенный круг вокруг местоположения пользователя. И есть слайдер за пределами карты, который может отрегулировать радиус круга. Размер круга также должен быть относительно уровня масштабирования, поэтому, если я увеличиваю все время, размер не становится действительно большим. Зум также трудно использовать, потому что уровень масштабирования сбрасывается каждый раз, когда я перемещаю ползунок.[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter.ScaleBarSettingsInterface.updateSettings.2"., null, null)
#0 ScaleBarSettingsInterface.updateSettings (package:mapbox_maps_flutter/src/pigeons/settings.dart:1138:7)

#1 _AreaCaptureScreenState._onMapCreated (package:sighttrack/screens/capture/area_capture.dart:37:5)

flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CameraManager.getCameraState.2"., null, null)
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CameraManager.getCameraState.2"., null, null)
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CircleAnnotationMessenger.deleteAll.1"., null, null)
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CircleAnnotationMessenger.deleteAll.1"., null, null)
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CameraManager.getCameraState.2"., null, null)
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CircleAnnotationMessenger.deleteAll.1"., null, null)
flutter: Error updating circle: PlatformException(channel-error, Unable to establish connection on channel: "dev.flutter.pigeon.mapbox_maps_flutter._CircleAnnotationMessenger.deleteAll.1"., null, null)
flutter: Error updating circle: Null check operator used on a null value
flutter: Error updating circle: Null check operator used on a null value
< /code>
Вот код страницы (клавиши API настроены на main.dart) < /p>
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';
import 'package:geolocator/geolocator.dart' as geo;

class AreaCaptureScreen extends StatefulWidget {
const AreaCaptureScreen({super.key});

@override
State createState() => _AreaCaptureScreenState();
}

class _AreaCaptureScreenState extends State {
MapboxMap? _mapboxMap;
CircleAnnotationManager? _circleManager;
CircleAnnotation? _circleAnnotation;
bool _isDisposed = false;
Point? _centerPoint;
double _radiusMeters = 300.0; // Non-final

@override
void dispose() {
_isDisposed = true;
super.dispose();
}

void _onMapCreated(MapboxMap mapboxMap) async {
if (_isDisposed || !mounted) return;
_mapboxMap = mapboxMap;

// Hide UI elements
await mapboxMap.logo.updateSettings(LogoSettings(enabled: false));
await mapboxMap.attribution.updateSettings(
AttributionSettings(enabled: false),
);
await mapboxMap.scaleBar.updateSettings(ScaleBarSettings(enabled: false));

// Enable location puck
await _mapboxMap!.location.updateSettings(
LocationComponentSettings(
enabled: true,
pulsingEnabled: true,
puckBearingEnabled: true,
),
);

try {
final geo.Position pos = await _determinePosition();
if (_isDisposed || !mounted) return;

_centerPoint = Point(coordinates: Position(pos.longitude, pos.latitude));
await _mapboxMap!.setCamera(
CameraOptions(center: _centerPoint, zoom: 15.0, bearing: pos.heading),
);

// Draw initial circle
await _updateCircle();
} catch (e) {
debugPrint('Error setting up map: $e');
}
}

Future _updateCircle() async {
if (_mapboxMap == null || _centerPoint == null || _isDisposed || !mounted)
return;

try {
// Initialize manager if not already set
_circleManager ??=
await _mapboxMap!.annotations.createCircleAnnotationManager();

// Calculate pixel radius
final cameraState = await _mapboxMap!.getCameraState();
final double groundResolution =
156543.03392 *
math.cos(_centerPoint!.coordinates.lat * math.pi / 180) /
math.pow(2, cameraState.zoom);
final double pixelRadius = _radiusMeters / groundResolution;

// Always create a new annotation to avoid ID issues
await _circleManager!.deleteAll(); // Clear existing annotations
_circleAnnotation = await _circleManager!.create(
CircleAnnotationOptions(
geometry: _centerPoint!,
circleRadius: pixelRadius,
circleColor: Color(0xFF33AFFF).toARGB32(),
circleOpacity: 0.3,
circleStrokeWidth: 1.5,
circleStrokeColor: Color(0xFF0077FF).toARGB32(),
),
);
} catch (e) {
debugPrint('Error updating circle: $e');
// Recreate manager on error to handle potential corruption
_circleManager = null;
if (mounted && !_isDisposed) {
_circleManager =
await _mapboxMap!.annotations.createCircleAnnotationManager();
await _updateCircle(); // Retry once
}
}
}

Future _determinePosition() async {
bool serviceEnabled = await geo.Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) throw Exception('Location services are disabled.');

geo.LocationPermission permission = await geo.Geolocator.checkPermission();
if (permission == geo.LocationPermission.denied) {
permission = await geo.Geolocator.requestPermission();
if (permission == geo.LocationPermission.denied) {
throw Exception('Location permissions are denied.');
}
}
if (permission == geo.LocationPermission.deniedForever) {
throw Exception('Location permissions are permanently denied.');
}

return await geo.Geolocator.getCurrentPosition();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.transparent,
foregroundColor: Colors.white,
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Container(
height: 300,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: MapWidget(
styleUri:
'',
cameraOptions: CameraOptions(
center: Point(coordinates: Position(-122.4194, 37.7749)),
zoom: 15.0,
),
onMapCreated: _onMapCreated,
onCameraChangeListener: (event) {
if (_circleAnnotation != null) {
_updateCircle();
}
},
key: UniqueKey(),
),
),
),
Slider(
value: _radiusMeters,
min: 100.0,
max: 1000.0,
onChanged: (newRadius) {
setState(() {
_radiusMeters = newRadius;
_updateCircle();
});
},
),
],
),
),
),
);
}
}



Подробнее здесь: https://stackoverflow.com/questions/795 ... ter-mapbox
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»