Skip to content

Instantly share code, notes, and snippets.

@venbrinoDev
Created May 17, 2025 15:31
Show Gist options
  • Save venbrinoDev/dd8802ce6effa1d3c96285407af9c178 to your computer and use it in GitHub Desktop.
Save venbrinoDev/dd8802ce6effa1d3c96285407af9c178 to your computer and use it in GitHub Desktop.

MapNavigationService Utility Class

import 'package:url_launcher/url_launcher.dart';
import 'dart:io';

class MapNavigationService {
  static Future<bool> navigateToGoogleMaps({
    required double destinationLat,
    required double destinationLng,
    String? destinationName,
  }) async {
    final String query = Uri.encodeComponent(
        destinationName ?? '$destinationLat,$destinationLng');

    String url;
    Uri uri;

    if (Platform.isAndroid) {
      // Android - Use Google Maps navigation
      url = 'google.navigation:q=$destinationLat,$destinationLng&mode=d';
      uri = Uri.parse(url);

      if (await canLaunchUrl(uri)) {
        return launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } else if (Platform.isIOS) {
      // iOS - Try Google Maps first
      url =
          'comgooglemaps://?daddr=$destinationLat,$destinationLng&directionsmode=driving';
      uri = Uri.parse(url);

      if (await canLaunchUrl(uri)) {
        return launchUrl(uri, mode: LaunchMode.externalApplication);
      }

      // If Google Maps isn't installed, fall back to Apple Maps
      url =
          'https://maps.apple.com/?daddr=$destinationLat,$destinationLng&dirflg=d';
      uri = Uri.parse(url);

      if (await canLaunchUrl(uri)) {
        return launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } else {
      // Web or other platforms - use a web URL
      url =
          'https://www.google.com/maps/dir/?api=1&destination=$query&travelmode=driving';
      uri = Uri.parse(url);

      if (await canLaunchUrl(uri)) {
        return launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    }

    // Last resort fallback to web Google Maps for all platforms
    final fallbackUrl =
        'https://www.google.com/maps/search/?api=1&query=$query';
    final fallbackUri = Uri.parse(fallbackUrl);

    if (await canLaunchUrl(fallbackUri)) {
      return launchUrl(fallbackUri, mode: LaunchMode.externalApplication);
    }

    return false;
  }
}```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment