🗾

【Flutter】GoogleMapに遷移しよう!

に公開

GoogleMapAPIを使うほどのでもないけど住所データをGoogleMapに渡したい!という場面に遭遇して意外と面倒だったので備忘録として書きます。
と言うのもiOSとAndroidOSで遷移する方法が異なります。
以下のような理由から対応が異なるということが想像できます。
AndroidOS→プリインストールされてる
iOS→プリインストールされてない
それぞれ対応が必要です。
iOSはGoogleMapのURLを用意して渡せばいいのですがAndroidはちょっと形式が異なるのでまとめます。

実装

まずはurl_launcherをインストールしてください
https://pub.dev/packages/url_launcher
iOSでは通常のHTTPリンクを用意してexternalApplicationで処理することで完成します。

dart
final encoded = Uri.encodeComponent(address);
final uri=Uri.parse('https://www.google.com/maps/search/?api=1&query=$encoded');
await launchUrl(uri, mode: LaunchMode.externalApplication);

これを関数に定義してやればiOSではブラウザかGoogleMapのアプリに遷移します。
Androidはgeoスキームを用意しないと遷移が行われない可能性があります。

final uri=Uri.parse('geo:0,0?q=$encoded')

これであとはurl_launcherを使えば遷移が行われます。Platform.isAndroidで端末によって使うURLを変えれば良いです。

dart
  final uri = Platform.isAndroid
      ? Uri.parse('geo:0,0?q=$encoded')
      : Uri.parse('https://www.google.com/maps/search/?api=1&query=$encoded');

コード全体

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

Future<void> openMapWithAddress(String address) async {
  final encoded = Uri.encodeComponent(address);
  final uri = Platform.isAndroid
      ? Uri.parse('geo:0,0?q=$encoded')
      : Uri.parse('https://www.google.com/maps/search/?api=1&query=$encoded');

  try {
    final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!launched) {
      log('launchUrl returned false: $uri');
    }
  } catch (e, st) {
    log('Could not launch $uri: $e', stackTrace: st);
  }
}

まとめ

今回は、「Google Maps API を組み込むほどではないけど、住所をマップアプリで開きたい」という場面で使えるシンプルな実装を紹介しました。

  • iOSでは https://www.google.com/maps/search/?query=住所 形式で遷移
  • Androidでは geo:0,0?q=住所 形式を使う必要がある
  • url_launcher パッケージと Platform.isAndroid を使えば、どちらも簡単にハンドリング可能

Flutterなら数行で実装できるので、ぜひ取り入れてみてください!

ぽちぽちのつどい

Discussion