Flutter地图位置选择插件google_map_location_picker的使用

Flutter地图位置选择插件google_map_location_picker的使用

google_map_location_picker 是一个基于官方 google_maps_flutter 插件的地图位置选择工具。由于谷歌已经弃用了旧版的 Place Picker,因此该插件被创建出来以替代之。

功能展示

以下是插件的一些功能截图:

使用方法

Pubspec 配置

pubspec.yaml 文件中添加以下依赖:

dependencies: 
  google_maps_flutter: ^0.5.30
  google_map_location_picker: ^3.3.4
  flutter_localizations:
    sdk: flutter

然后在 MaterialApp 中配置本地化支持:

import 'package:google_map_location_picker/generated/l10n.dart' as location_picker;
import 'package:flutter_localizations/flutter_localizations.dart';

MaterialApp(
  localizationsDelegates: const [
    location_picker.S.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const <Locale>[
    Locale('en', ''),
    Locale('ar', ''),
  ],
  home: ...
)
基本用法

通过调用 showLocationPicker 方法打开地图并选择位置:

import 'package:google_map_location_picker/google_map_location_picker.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

LocationResult result = await showLocationPicker(context, apiKey);

获取开始

获取API密钥
  1. 访问 Google Cloud Console 并获取一个API密钥。
  2. Google Cloud Console 中启用以下API:
    • Maps SDK for Android
    • Maps SDK for iOS
    • Places API
    • Geolocation API
    • Geocoding API
  3. 确保为项目启用了计费功能。
Android 配置

android/app/src/main/AndroidManifest.xml 中添加API密钥:

<manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>
</manifest>
iOS 配置

ios/Runner/AppDelegate.m 中添加API密钥:

#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GMSServices provideAPIKey:@"YOUR KEY HERE"];
  [GeneratedPluginRegistrant registerWithRegistry:self];
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

或者在 Swift 中:

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

同时,需要定义 NSLocationWhenInUseUsageDescription

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs your location to test the location feature of the Google Maps location picker plugin.</string>
注意事项
  • Android设备需要以下权限(推荐):
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  • 如果目标版本为Android 5.0及以上,且需要网络或GPS定位,请显式声明硬件特性:
    <uses-feature android:name="android.hardware.location.network" android:required="false" />
    <uses-feature android:name="android.hardware.location.gps" android:required="false" />
    

限制自动补全搜索区域

可以通过传递国家代码数组来限制自动补全搜索的区域。例如,仅允许搜索阿联酋和尼日利亚:

showLocationPicker(
  context, 
  "YOUR API KEY HERE",
  initialCenter: LatLng(31.1975844, 29.9598339),
  myLocationButtonEnabled: true,
  layersButtonEnabled: true,
  countries: ['AE', 'NG'],
);

完整示例代码

以下是一个完整的示例代码,展示了如何使用 google_map_location_picker 插件:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:google_map_location_picker/generated/l10n.dart' as location_picker;
import 'package:google_map_location_picker/google_map_location_picker.dart';
import 'package:google_map_location_picker_example/keys.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import 'generated/i18n.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  LocationResult _pickedLocation;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'location picker',
      localizationsDelegates: const [
        location_picker.S.delegate,
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const <Locale>[
        Locale('en', ''),
        Locale('ar', ''),
        Locale('pt', ''),
        Locale('tr', ''),
        Locale('es', ''),
        Locale('it', ''),
        Locale('ru', ''),
      ],
      home: Scaffold(
        appBar: AppBar(
          title: const Text('location picker'),
        ),
        body: Builder(builder: (context) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                RaisedButton(
                  onPressed: () async {
                    LocationResult result = await showLocationPicker(
                      context,
                      apiKey,
                      initialCenter: LatLng(31.1975844, 29.9598339),
                      myLocationButtonEnabled: true,
                      layersButtonEnabled: true,
                      desiredAccuracy: LocationAccuracy.best,
                    );
                    print("result = $result");
                    setState(() => _pickedLocation = result);
                  },
                  child: Text('Pick location'),
                ),
                Text(_pickedLocation?.toString() ?? ''),
              ],
            ),
          );
        }),
      ),
    );
  }
}

更多关于Flutter地图位置选择插件google_map_location_picker的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地图位置选择插件google_map_location_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


google_map_location_picker 是一个用于在 Flutter 应用中集成 Google 地图并允许用户选择位置的插件。它提供了一个简单的方式来让用户在地图上选择一个位置,并返回该位置的经纬度、地址等信息。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 google_map_location_picker 依赖:

dependencies:
  flutter:
    sdk: flutter
  google_map_location_picker: ^4.1.3

然后运行 flutter pub get 来安装依赖。

配置 Google Maps API

在使用 google_map_location_picker 之前,你需要在 Google Cloud Console 中启用 Google Maps API 并获取 API 密钥。

  1. 前往 Google Cloud Console
  2. 创建一个新项目或选择现有项目。
  3. 启用 Maps SDK for AndroidMaps SDK for iOS
  4. API 密钥 部分创建一个新的 API 密钥。
  5. android/app/src/main/AndroidManifest.xmlios/Runner/AppDelegate.swift 中配置 API 密钥。

AndroidManifest.xml:

<manifest ...
    <application ...
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY"/>
    </application>
</manifest>

AppDelegate.swift:

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR_API_KEY")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

使用 google_map_location_picker

在你的 Flutter 应用中,你可以使用 GoogleMapLocationPicker 来让用户选择位置。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:google_map_location_picker/google_map_location_picker.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location Picker'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            LocationResult result = await showLocationPicker(
              context,
              "YOUR_API_KEY",
              initialCenter: LatLng(37.4219999, -122.0840575), // 初始位置
              automaticallyAnimateToCurrentLocation: true, // 自动定位到当前位置
              myLocationButtonEnabled: true, // 显示“我的位置”按钮
              layersButtonEnabled: true, // 显示图层按钮
              desiredAccuracy: LocationAccuracy.high, // 定位精度
            );

            print("Selected Location: ${result.address}");
            print("Latitude: ${result.latLng.latitude}");
            print("Longitude: ${result.latLng.longitude}");
          },
          child: Text('Pick Location'),
        ),
      ),
    );
  }
}
回到顶部