Flutter地点选择插件flutter_place_picker的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter地点选择插件flutter_place_picker的使用

介绍

flutter_place_picker 是一个Flutter插件,允许用户通过Open Street Map、Here Maps和Google Maps小部件来选择地点。该插件依赖于以下包:

  • google_maps_flutter:用于显示地图。
  • geolocator:用于获取当前设备的位置。
  • google_maps_webservice:用于调用Google Places API和Geocoding API。
  • tuple:用于构建。

此外,该项目还提供了一个Laravel(PHP框架)服务器,你可以将其托管在自己的服务器上。

预览

预览

开始使用

获取API密钥
  1. Google Cloud Console获取API密钥。
  2. 启用Google Maps SDK:
    • 进入Google Developers Console
    • 选择你要启用Google Maps的项目。
    • 选择导航菜单,然后选择“Google Maps”。
    • 在Google Maps菜单下选择“APIs”。
    • 启用“Maps SDK for Android”和“Maps SDK for iOS”。
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"/>

注意:从版本3.0.0开始,geolocator插件切换到了AndroidX版本的Android支持库。你需要确保你的Android项目也升级到支持AndroidX。具体步骤如下:

  1. gradle.properties文件中添加以下内容:
android.useAndroidX=true
android.enableJetifier=true
  1. 确保在android/app/build.gradle文件中将compileSdkVersion设置为28:
android {
  compileSdkVersion 28

  ...
}
  1. 将所有android.依赖项替换为它们的AndroidX对应项。
iOS配置

ios/Runner/AppDelegate.m中指定API密钥:

#include "AppDelegate.h"
#include "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代码中,在ios/Runner/AppDelegate.swift中指定API密钥:

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 KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

在iOS中,你还需要在Info.plist文件中添加以下条目以访问设备的位置:

<key>NSLocationWhenInUseUsageDescription</key>
<string>此应用在打开时需要访问位置。</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>此应用在后台时需要访问位置。</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>此应用在打开和后台时需要访问位置。</string>

此外,你需要在XCode项目中添加“Background Modes”功能,并选择“Location Updates”。同时,启用嵌入式视图预览,方法是在Info.plist文件中添加以下条目:

<key>io.flutter.embedded_views_preview</key>
<true/>

使用示例

基本用法

你可以通过Navigator推送一个新的页面来使用PlacePicker,或者将其作为任何小部件的子级。当用户在地图上选择一个地点时,它会通过onPlacePicked回调返回结果。

Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => FlutterPlacePicker(
      apiKey: "YOUR KEY HERE", // 替换为你的API密钥
      onPlacePicked: (result) {
        Navigator.of(context).pop();
        // 处理选择的地点
        print(result.geometry!.location.lat);
        print(result.geometry!.location.lng);
        print(result.placeId);
        print(result.formattedAddress);
      },
      initialPosition: HomePage.kInitialPosition,
      useCurrentLocation: true,
    ),
  ),
);
自定义选中地点的可视化

默认情况下,当用户通过自动完成搜索或拖动地图选择地点时,会在屏幕底部显示信息(FloatingCard)。如果你不喜欢这个UI/UX,可以通过覆盖selectedPlaceWidgetBuilder来自定义。

PlacePicker(
  apiKey: "YOUR KEY HERE",
  selectedPlaceWidgetBuilder: (_, selectedPlace, state, isSearchBarFocused) {
    return isSearchBarFocused
        ? Container()
        : FloatingCard(
            bottomPosition: 0.0,
            leftPosition: 0.0,
            rightPosition: 0.0,
            width: 500,
            borderRadius: BorderRadius.circular(12.0),
            child: state == SearchingState.Searching
                ? Center(child: CircularProgressIndicator())
                : ElevatedButton(
                    onPressed: () {
                      print("do something with [selectedPlace] data");
                      Navigator.of(context).pop();
                    },
                    child: Text("Pick Here"),
                  ),
          );
  },
  ...
)
自定义Pin

你可以通过pinBuilder来自定义Pin图标。

FlutterPlacePicker(
  apiKey: "YOUR KEY HERE",
  pinBuilder: (context, state) {
    if (state == PinState.Idle) {
      return Icon(Icons.favorite_border);
    } else {
      return AnimatedIcon(
        icon: AnimatedIcons.search_ellipsis,
        progress: AnimationController(vsync: this),
      );
    }
  },
  ...
)
更改默认FloatingCard的颜色

你可以通过themeData来更改默认FloatingCard的样式。

final ThemeData lightTheme = ThemeData.light().copyWith(
  cardColor: Colors.white,
  buttonTheme: ButtonThemeData(
    buttonColor: Colors.black,
    textTheme: ButtonTextTheme.primary,
  ),
);

final ThemeData darkTheme = ThemeData.dark().copyWith(
  cardColor: Colors.grey,
  buttonTheme: ButtonThemeData(
    buttonColor: Colors.yellow,
    textTheme: ButtonTextTheme.primary,
  ),
);

完整示例Demo

以下是一个完整的示例应用程序,展示了如何使用flutter_place_picker插件。

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

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

class MyApp extends StatelessWidget {
  final ThemeData lightTheme = ThemeData.light().copyWith(
    cardColor: Colors.white,
    buttonTheme: const ButtonThemeData(
      buttonColor: Colors.black,
      textTheme: ButtonTextTheme.primary,
    ),
  );

  final ThemeData darkTheme = ThemeData.dark().copyWith(
    cardColor: Colors.grey,
    buttonTheme: const ButtonThemeData(
      buttonColor: Colors.yellow,
      textTheme: ButtonTextTheme.primary,
    ),
  );

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Place Picker Demo',
      theme: lightTheme,
      darkTheme: darkTheme,
      themeMode: ThemeMode.light,
      home: const HomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PickResult? selectedPlace;
  final LatLng kInitialPosition = const LatLng(-33.8567844, 151.213108);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Google Map Place Picker Demo"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              child: const Text("Load Google Map"),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) {
                      return FlutterPlacePicker(
                        apiKey: "YOUR KEY HERE", // 替换为你的API密钥
                        initialPosition: kInitialPosition,
                        useCurrentLocation: true,
                        selectInitialPosition: true,
                        usePlaceDetailSearch: false,
                        region: 'gh',
                        strictBounds: true,
                        onPlacePicked: (result) {
                          selectedPlace = result;

                          print(result.geometry!.location.lat);
                          print(result.geometry!.location.lng);
                          print(result.placeId);
                          print(result.formattedAddress);

                          Navigator.of(context).pop();
                          setState(() {});
                        },
                      );
                    },
                  ),
                );
              },
            ),
            selectedPlace == null
                ? Container()
                : Text(selectedPlace!.formattedAddress ?? ""),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_place_picker插件来选择地点的代码示例。这个插件允许用户从地图上选择一个地点,并返回该地点的详细信息。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_place_picker: ^0.9.19  # 请检查最新版本号并替换

然后,运行flutter pub get来获取依赖。

接下来,你可以在你的Flutter应用中使用这个插件。以下是一个简单的示例,展示了如何集成和使用flutter_place_picker

import 'package:flutter/material.dart';
import 'package:flutter_place_picker/flutter_place_picker.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Place Picker Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PlacePickerExample(),
    );
  }
}

class PlacePickerExample extends StatefulWidget {
  @override
  _PlacePickerExampleState createState() => _PlacePickerExampleState();
}

class _PlacePickerExampleState extends State<PlacePickerExample> {
  PlaceResult? _selectedPlace;

  Future<void> _selectPlace() async {
    final result = await PlacePicker.showPicker(
      context,
      apiKey: 'YOUR_GOOGLE_MAPS_API_KEY',  // 请替换为你的Google Maps API Key
      initialPosition: LatLng(37.7749, -122.4194),  // 初始位置(旧金山)
      useCurrentLocation: true,
      selectionMode: SelectionMode.single,
    );

    if (result != null) {
      setState(() {
        _selectedPlace = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Place Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _selectPlace,
              child: Text('Select Place'),
            ),
            SizedBox(height: 20),
            if (_selectedPlace != null)
              Text(
                'Selected Place: ${_selectedPlace!.name}, Latitude: ${_selectedPlace!.geometry!.location!.lat}, Longitude: ${_selectedPlace!.geometry!.location!.lng}',
                style: TextStyle(fontSize: 18),
              ),
          ],
        ),
      ),
    );
  }
}

注意事项:

  1. Google Maps API Key:你需要一个有效的Google Maps API Key来使用该插件。确保你已经在Google Cloud Platform上启用了Places API和Maps JavaScript API,并将API Key添加到你的项目中。
  2. 权限:如果你的应用需要访问用户的当前位置,请确保在AndroidManifest.xmlInfo.plist文件中添加了必要的权限声明。

AndroidManifest.xml 示例(添加位置权限):

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Info.plist 示例(添加位置权限):

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when in use</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in use</string>

以上代码展示了如何在Flutter应用中使用flutter_place_picker插件来选择地点,并显示所选地点的名称和经纬度信息。希望这对你有所帮助!

回到顶部