Flutter 谷歌地图应用

一个崭新的 Flutter 项目。

入门

Flutter 项目

  • 将此添加到您的 package 的 pubspec.yaml 文件中

    依赖项: map_view: "^0.0.12"

入门

生成您的 API 密钥

  1. 前往: https://console.developers.google.com/
  2. 启用 Google Maps Android API
  3. 启用 Google Maps SDK for iOS
  4. 凭据下,选择 创建凭据
    • 注意:对于开发,您可以创建一个不受限制的 API 密钥,该密钥可用于 iOS 和 Android。
      对于生产环境,强烈建议您限制。

注册 API 密钥的方式在 iOS 和 Android 上有所不同。请务必仔细阅读以下各部分。

iOS

地图插件在需要时会请求用户的位置。iOS 要求您在 Info.plist 文件中解释此用法

  1. ios/Runner/Info.plist 中设置 NSLocationWhenInUseUsageDescription。例如
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Using location to display on a map</string>
  1. 在使用地图插件之前,您必须调用 MapView.setApiKey(String apiKey)。例如
   import 'package:map_view/map_view.dart';
   
   void main() {
     MapView.setApiKey("<your_api_key>");
     runApp(new MyApp());
   }

注意:如果您的 iOS 和 Android API 密钥不同,请务必在此处使用您的 iOS API 密钥。

  1. 添加代码以显示 MapView。

    //Create an instance variable for the mapView
    var _mapView = new MapView();
    
    
    //Add a method to call to show the map.
    void showMap() {
        _mapView.show(new MapOptions(showUserLocation: true));
    }
      
    
    
  2. 在 iOS 设备或模拟器上运行您的应用程序。
    确认显示地图时可以看到地图详细信息。
    如果您只看到米色屏幕,则可能是您的 API 密钥不正确。当您的 API
    密钥不正确时,您会在控制台中看到类似这样的消息

ClientParametersRequest failed, 7 attempts remaining (0 vs 12). Error Domain=com.google.HTTPStatus Code=400 "(null)" UserInfo={data=<>}

iOS 常见的 API 密钥问题

  1. 您的 Bundle ID 与 Google API 控制台中注册的 Bundle ID 不匹配。
    当您在 Google API 控制台中创建受限制的 API 密钥时,它会要求您指定 iOS Bundle ID。
    请确保您的 iOS Bundle Identifier 与您在控制台中注册的 Bundle Identifier 匹配。

  2. 使用错误的密钥。如果您为 iOS 和 Android 创建了单独的密钥,
    请确保您在 MapView.setApiKey() 调用中使用的是 iOS 密钥。

Android

您将对 AndroidManifest.xml 文件进行多次编辑。在您的 Flutter 项目中,您可以
在此文件位置找到 android/app/src/main

  1. 在您的 AndroidManifest.xml 文件中,在标记上方添加以下 uses-permission。

        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    
  2. 在您的 AndroidManifest.xml 文件中,在 application 标记内添加以下行。请务必将 your_api_key 替换为您生成的密钥。

        <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_api_key"/>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
    
  3. 将 MapActivity 添加到您的 AndroidManifest.xml 文件中

        <activity android:name="com.apptreesoftware.mapview.MapActivity" android:theme="@style/Theme.AppCompat.Light.DarkActionBar"/>
    
  4. 在您的 android/build.gradle 文件中。在 buildScript dependencies 下添加

        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-4'
    
  5. 在 Android 设备或模拟器上运行您的应用程序。
    确认显示地图时可以看到地图详细信息。
    如果您只看到米色屏幕,则可能是您的 API 密钥不正确。

GitHub

https://github.com/iampawan/FlutterGoogleMaps