Skip to main content

bardiyamap_flutter 0.1.0 copy "bardiyamap_flutter: ^0.1.0" to clipboard
bardiyamap_flutter: ^0.1.0 copied to clipboard

MapLibre map widget for Bardiya Map with backend-proxied styles, route and marker overlays, and no API keys in the application bundle.

example/lib/main.dart

import 'dart:async';

import 'package:bardiyamap_flutter/bardiyamap_flutter.dart';
import 'package:flutter/material.dart';

/// Bardiya Map Flutter example covering:
/// - Key-free MapLibre map display using a backend-proxied style URL
/// - Markers, route rendering, live location puck, and camera fitting
/// - Customer-backend-proxied Places search, autocomplete, and Arabic geocoding
/// - Session-scoped device ingest (`BardiyaIngest`) and lifecycle-managed SSE
///   realtime streaming (`BardiyaRealtimeController`) with clean disposal
///
/// Run with:
///   flutter run \
///     --dart-define=STYLE_URL=https://your-backend.example/bardiya/style.json \
///     --dart-define=PROXY_BASE_URL=https://your-backend.example/bardiya
const _styleUrl = String.fromEnvironment('STYLE_URL');
const _proxyBaseUrl = String.fromEnvironment('PROXY_BASE_URL');
const _sessionId = String.fromEnvironment('TRACKING_SESSION_ID');
const _ingestCredential = String.fromEnvironment('INGEST_CREDENTIAL');
const _organizationId = String.fromEnvironment('ORGANIZATION_ID');

void main() => runApp(const ExampleApp());

class ExampleApp extends StatelessWidget {
  const ExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bardiya Map Flutter Example',
      theme: ThemeData(colorSchemeSeed: const Color(0xFF0B6E4F)),
      home: const BardiyaDemoHome(),
    );
  }
}

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

  @override
  State<BardiyaDemoHome> createState() => _BardiyaDemoHomeState();
}

class _BardiyaDemoHomeState extends State<BardiyaDemoHome> {
  BardiyaMapController? _mapController;
  BardiyaClient? _proxyClient;
  BardiyaIngest? _ingest;
  BardiyaRealtimeController? _realtime;
  StreamSubscription<BardiyaStreamEvent>? _realtimeSub;

  final BardiyaRoute _route = const BardiyaRoute(coordinates: [
    BardiyaCoordinate(latitude: 30.0444, longitude: 31.2357),
    BardiyaCoordinate(latitude: 30.0626, longitude: 31.2497),
  ]);
  BardiyaLocation _location = const BardiyaLocation(
    latitude: 30.0444,
    longitude: 31.2357,
    accuracyMeters: 10,
  );
  List<BardiyaMarker> _markers = const [
    BardiyaMarker(
      id: 'tahrir',
      latitude: 30.0444,
      longitude: 31.2357,
      label: 'Tahrir Square',
    ),
    BardiyaMarker(
      id: 'nasr-city',
      latitude: 30.0626,
      longitude: 31.2497,
      label: 'مدينة نصر',
    ),
  ];
  String _status = 'Ready';

  @override
  void initState() {
    super.initState();
    if (_proxyBaseUrl.isNotEmpty) {
      // Customer backend proxies Maps requests and attaches the server API key.
      _proxyClient = BardiyaClient(BardiyaConfig(baseUrl: _proxyBaseUrl));
    }
    if (_sessionId.isNotEmpty && _ingestCredential.isNotEmpty) {
      // Device ingest uses a short-lived, session-scoped credential only.
      _ingest = BardiyaIngest(
        sessionId: _sessionId,
        credential: _ingestCredential,
        organizationId: _organizationId.isEmpty ? null : _organizationId,
      );
      _realtime = BardiyaRealtimeController(
        streamFactory: () => BardiyaStreamClient(
          sessionId: _sessionId,
          bearerToken: _ingestCredential,
          organizationId: _organizationId.isEmpty ? null : _organizationId,
        ).stream(),
      );
      _realtimeSub = _realtime!.events.listen(_handleRealtimeEvent);
      unawaited(_realtime!.start());
    }
  }

  void _handleRealtimeEvent(BardiyaStreamEvent event) {
    if (!mounted) return;
    if (event.isLocation || event.isSnapshot) {
      final decoded = event.decoded;
      if (decoded is Map &&
          decoded['latitude'] is num &&
          decoded['longitude'] is num) {
        setState(() {
          _location = BardiyaLocation(
            latitude: (decoded['latitude'] as num).toDouble(),
            longitude: (decoded['longitude'] as num).toDouble(),
          );
          _status = 'Realtime ${event.event} (${event.id ?? "snapshot"})';
        });
      }
    }
  }

  Future<void> _searchArabicAddress() async {
    final client = _proxyClient;
    if (client == null) {
      setState(() => _status = 'Configure PROXY_BASE_URL to query backend.');
      return;
    }
    try {
      final suggestions =
          await client.places.autocompletePlaces('مدينة نصر');
      final geocoded =
          await client.geocoding.forwardGeocode('شارع التحرير، القاهرة');
      final first = geocoded?.results.firstOrNull;
      final lat = first?.latitude;
      final lon = first?.longitude;
      if (first != null && lat != null && lon != null && mounted) {
        setState(() {
          _markers = [
            ..._markers,
            BardiyaMarker(
              id: 'arabic-geocode',
              latitude: lat,
              longitude: lon,
              label: first.name,
            ),
          ];
          _status =
              'Autocomplete: ${suggestions?.suggestions.length ?? 0}, '
              'Geocode: ${first.name}';
        });
        await _mapController?.animateCamera(
          BardiyaCoordinate(latitude: lat, longitude: lon),
          zoom: 14,
        );
      }
    } on BardiyaApiException catch (err) {
      if (mounted) {
        setState(() => _status = 'API error ${err.error.code}');
      }
    }
  }

  Future<void> _sendSampleLocation() async {
    final ingest = _ingest;
    if (ingest == null) {
      setState(
        () => _status = 'Configure TRACKING_SESSION_ID and INGEST_CREDENTIAL.',
      );
      return;
    }
    try {
      await ingest.sendLocation(TrackingIngestEventCreate(
        clientEventId: 'demo-${DateTime.now().microsecondsSinceEpoch}',
        clientSeq: DateTime.now().millisecondsSinceEpoch,
        recordedAt: DateTime.now().toUtc(),
        eventType: TrackingIngestEventCreateEventTypeEnum.location,
        latitude: _location.latitude,
        longitude: _location.longitude,
      ));
      if (mounted) setState(() => _status = 'Location ingested');
    } on BardiyaApiException catch (err) {
      if (mounted) {
        setState(() => _status = 'Ingest failed: ${err.error.code}');
      }
    }
  }

  @override
  void dispose() {
    unawaited(_realtimeSub?.cancel());
    unawaited(_realtime?.dispose());
    _ingest?.close();
    _proxyClient?.close();
    _mapController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Bardiya Map')),
      body: Column(
        children: [
          Material(
            elevation: 1,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              child: Row(
                children: [
                  Expanded(child: Text(_status, maxLines: 2)),
                  TextButton(
                    onPressed: _searchArabicAddress,
                    child: const Text('Arabic Geocode'),
                  ),
                  TextButton(
                    onPressed: () => _mapController?.fitRoute(_route),
                    child: const Text('Fit Route'),
                  ),
                  TextButton(
                    onPressed: _sendSampleLocation,
                    child: const Text('Send GPS'),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: _styleUrl.isEmpty
                ? const Center(
                    child: Padding(
                      padding: EdgeInsets.all(24),
                      child: Text(
                        'Pass a proxied style URL:\n'
                        'flutter run --dart-define=STYLE_URL=https://…',
                        textAlign: TextAlign.center,
                      ),
                    ),
                  )
                : BardiyaMap(
                    style: _styleUrl,
                    initialCameraPosition: const CameraPosition(
                      target: LatLng(30.0444, 31.2357),
                      zoom: 12,
                    ),
                    route: _route,
                    markers: _markers,
                    location: _location,
                    onBardiyaMapCreated: (controller) {
                      _mapController = controller;
                    },
                  ),
          ),
        ],
      ),
    );
  }
}
0
likes
150
points
--
downloads

Documentation

API reference

Publisher

verified publisherbardiyamap.com

Weekly Downloads

MapLibre map widget for Bardiya Map with backend-proxied styles, route and marker overlays, and no API keys in the application bundle.

Homepage
View/report issues

Topics

#maps #maplibre #flutter

License

Apache-2.0 (license)

Dependencies

bardiyamap_sdk, flutter, maplibre_gl

More

Packages that depend on bardiyamap_flutter