Flutter地理位置选择插件bound_location_picker的使用

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

Flutter地理位置选择插件bound_location_picker的使用

插件介绍

bound_location_picker 是一个由官方 google_maps_flutter 插件创建的Flutter包,可以帮助你在边界内选择位置。该插件支持Android、iOS和Web平台。

主要功能

  • 在多边形边界内选择位置
  • 在圆形边界内选择位置

开发者信息

该插件由@Hasan开发。

支持版本

平台 Android iOS Web
SDK 20+ 11+ 同步于Flutter

示例代码

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: BoundLocationPicker(
          initialCameraPosition: const LatLng(24.540725, 89.631088),
          onPickedLocation: (LatLng? location) {
            ///TODO do something using location
          },
          onLocationUpdateListener: (LatLng? location) {
            ///TODO do something with current location
          },
          locationPickerImage: const AssetImage("assets/pin_point.png"),
          circleBoundary: CircleBoundary(radius: 800),
          enablePickedButton: true,
        ),
      ),
    );
  }
}

使用说明

1 添加依赖pubspec.yaml文件中添加bound_location_picker作为依赖项。

dependencies:
  flutter:
    sdk: flutter

  bound_location_picker: ^update_version

确保执行flutter pub get以安装依赖项。

Android配置

1 设置最小SDK版本android/app/build.gradle中设置minSdkVersion

android {
    defaultConfig {
        minSdkVersion 20
    }
}

这意味着应用仅适用于运行Android SDK 20或更高版本的用户。

1 指定API密钥android/app/src/main/AndroidManifest.xml中指定API密钥。

<manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/&gt;
</manifest>

iOS配置

1 指定API密钥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]?
  ) -&gt; Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Web配置

1 修改web/index.html文件 将Google Maps JS SDK包含到您的Flutter Web应用程序的web/index.html文件中。 请参阅google_maps_flutter_web README获取如何准备您的应用以在Web上使用Google Maps的最新信息。

示例代码

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: BoundLocationPicker(
          initialCameraPosition: const LatLng(24.540725, 89.631088),
          onPickedLocation: (LatLng? location) {
            ///TODO do something using location
          },
          onLocationUpdateListener: (LatLng? location) {
            ///TODO do something with current location
          },
          locationPickerImage: const AssetImage("assets/pin_point.png"),
          circleBoundary: CircleBoundary(radius: 800),
          enablePickedButton: true,
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用bound_location_picker插件的一个简单示例。这个插件允许用户选择一个地理位置,并且可以在地图上定义一个边界框(bounding box)来限制选择范围。

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

dependencies:
  flutter:
    sdk: flutter
  bound_location_picker: ^最新版本号  # 请替换为实际的最新版本号

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

接下来,在你的Dart文件中使用BoundLocationPicker。以下是一个完整的示例,展示如何集成和使用这个插件:

import 'package:flutter/material.dart';
import 'package:bound_location_picker/bound_location_picker.dart';
import 'package:geolocator/geolocator.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bound Location Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  BoundLocationData? _selectedLocation;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bound Location Picker Demo'),
      ),
      body: Center(
        child: _selectedLocation == null
            ? ElevatedButton(
                onPressed: () async {
                  // 获取当前位置作为初始中心点和边界框的中心
                  Position currentPosition = await Geolocator.getCurrentPosition(
                    desiredAccuracy: LocationAccuracy.high,
                  );

                  // 打开位置选择器
                  BoundLocationData? result = await showBoundLocationPicker(
                    context: context,
                    initialCenter: LatLng(currentPosition.latitude!, currentPosition.longitude!),
                    initialBounds: LatLngBounds(
                      northeast: LatLng(currentPosition.latitude! + 0.01, currentPosition.longitude! + 0.01),
                      southwest: LatLng(currentPosition.latitude! - 0.01, currentPosition.longitude! - 0.01),
                    ),
                  );

                  // 更新状态
                  setState(() {
                    _selectedLocation = result;
                  });
                },
                child: Text('Select Location'),
              )
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Selected Location:'),
                  Text('Latitude: ${_selectedLocation!.latitude}'),
                  Text('Longitude: ${_selectedLocation!.longitude}'),
                  Text('Northeast: Latitude: ${_selectedLocation!.bounds!.northeast!.latitude}, Longitude: ${_selectedLocation!.bounds!.northeast!.longitude}'),
                  Text('Southwest: Latitude: ${_selectedLocation!.bounds!.southwest!.latitude}, Longitude: ${_selectedLocation!.bounds!.southwest!.longitude}'),
                ],
              ),
      ),
    );
  }
}

在这个示例中,我们首先导入了必要的包,然后创建了一个简单的Flutter应用。在MyHomePage中,我们定义了一个_selectedLocation变量来存储用户选择的位置数据。当用户点击按钮时,我们使用Geolocator插件获取当前位置作为初始中心点和边界框的中心,然后打开BoundLocationPicker让用户选择一个位置。选择完成后,我们更新UI以显示选定的位置和边界框信息。

请注意,为了使用Geolocator插件,你还需要在android/app/src/main/AndroidManifest.xml文件中添加必要的权限:

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

并且在iOS项目中,你需要在Info.plist中添加相应的权限描述。

希望这个示例对你有所帮助!

回到顶部