0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutter WebでGoogleMapAPIなどを動的に渡したい

Posted at

今回使用するパッケージ

パッケージインストール

$ flutter pub add google_maps_flutter
pubspec.yaml
dependencies:
  google_maps_flutter: ^2.10.0

通常の導入

  • GoogleMapApiをindex.htmlの<head>タグに埋め込む
<html>
    <!-- 省略 -->
    <head>
+     <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
    </head>
    <body>
        <script src="flutter_bootstrap.js" async></script>
    </body>
</html>

動的に渡す場合

  • index.htmlではAPIKeyの設定をしない
<html>
    <!-- 省略 -->
    <head>
- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
+ 
    </head>
    <body>
        <script src="flutter_bootstrap.js" async></script>
    </body>
</html>
  • APIの設定はFlutter側で設定をする
    下記警告が出るので&loading=async&callback=initMapを追加しています
Google Maps JavaScript API has been loaded directly without loading=async. This can result in suboptimal performance. For best-practice loading patterns please see https://goo.gle/js-api-loading
main.dart
import 'package:js/js_util.dart' as js_util;
import 'package:flutter/foundation.dart';

void main(){
 if (kIsWeb) {
  const googleMapApiKey = String.fromEnvironment('GOOGLE_MAP_API_KEY_WEB');
  // documentを取得
  final document = js_util.getProperty(js_util.globalThis, 'document');
  // <script> 要素を作成
  final script = js_util.callMethod(document, 'createElement', ['script']);
  // <script> 要素のsrc属性にGoogle Maps APIのURLを設定
  // loading=async と callback=initMap を追加
  final googleMapUrl =
     "https://maps.googleapis.com/maps/api/js?key=$googleMapApiKey&libraries=drawing,visualization,places&loading=async&callback=initMap";
     
  // <script>要素の設定
  js_util.setProperty(script, 'src', googleMapUrl);
  js_util.setProperty(script, 'async', true); // 要らないかもです
  js_util.setProperty(script, 'defer', true);
  
  // <head>に <script> 要素を挿入
  final head = js_util.callMethod(document, 'querySelector', ['head']);
  js_util.callMethod(head, 'appendChild', [script]);
  
  // コールバック関数を設定する
  js_util.setProperty(js_util.globalThis, 'initMap', js_util.allowInterop(() {
   print('Google Maps API loaded successfully!');
   // 地図の描画などの処理を開始
  }));
 }
 runApp(const MyApp());
}

起動時のコマンド

$ flutter run --dart-define=GOOGLE_MAP_API_KEY_WEB=XXXXXXXXXXXXXXXXXXX

ビルド時のコマンド

$ flutter build web --dart-define=GOOGLE_MAP_API_KEY_WEB=XXXXXXXXXXXXXXXXXXX
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?