这是用户在 2024-5-13 10:34 为 https://pub-web.flutter-io.cn/packages/geolocator 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

geolocator 11.0.0  地理定位器11.0.0copy "geolocator: ^11.0.0" to clipboard
geolocator: ^11.0.0 copied to clipboard

Geolocation plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API for generic location (GPS etc.) functions.
Flutter 的地理定位插件。该插件为通用位置(GPS 等)功能提供跨平台(iOS、Android)API。

Flutter Geolocator Plugin #
Flutter 地理定位器插件 #

pub package Build status style: effective dart codecov

A Flutter geolocation plugin which provides easy access to platform specific location services (FusedLocationProviderClient or if not available the LocationManager on Android and CLLocationManager on iOS).
Flutter 地理定位插件,可轻松访问特定于平台的位置服务(FusedLocationProviderClient,或者如果不可用,则为 Android 上的 LocationManager 和 iOS 上的 CLLocationManager)。

Features # 特征 #

  • Get the last known location;
    获取最后已知位置;
  • Get the current location of the device;
    获取设备当前位置;
  • Get continuous location updates;
    获取持续的位置更新;
  • Check if location services are enabled on the device;
    检查设备是否开启定位服务;
  • Calculate the distance (in meters) between two geocoordinates;
    计算两个地理坐标之间的距离(以米为单位);
  • Calculate the bearing between two geocoordinates;
    计算两个地理坐标之间的方位角;

IMPORTANT: 重要的:

Version 7.0.0 of the geolocator plugin contains several breaking changes, for a complete overview please have a look at the Breaking changes in 7.0.0 wiki page.
地理定位器插件 7.0.0 版本包含多项重大更改,有关完整概述,请查看 7.0.0 维基页面中的重大更改。

Starting from version 6.0.0 the geocoding features (placemarkFromAddress and placemarkFromCoordinates) are no longer part of the geolocator plugin. We have moved these features to their own plugin: geocoding. This new plugin is an improved version of the old methods.
从版本 6.0.0 开始,地理编码功能( placemarkFromAddressplacemarkFromCoordinates )不再是地理定位器插件的一部分。我们已将这些功能转移到他们自己的插件中:地理编码。这个新插件是旧方法的改进版本。

Usage # 用法 #

To add the geolocator to your Flutter application read the install instructions. Below are some Android and iOS specifics that are required for the geolocator to work correctly.
要将地理定位器添加到您的 Flutter 应用程序中,请阅读安装说明。以下是地理定位器正常工作所需的一些 Android 和 iOS 细节。

Android 安卓

Upgrade pre 1.12 Android projects
升级 1.12 之前的 Android 项目

Since version 5.0.0 this plugin is implemented using the Flutter 1.12 Android plugin APIs. Unfortunately this means App developers also need to migrate their Apps to support the new Android infrastructure. You can do so by following the Upgrading pre 1.12 Android projects migration guide. Failing to do so might result in unexpected behaviour.
从 5.0.0 版本开始,该插件是使用 Flutter 1.12 Android 插件 API 实现的。不幸的是,这意味着应用程序开发人员还需要迁移他们的应用程序以支持新的 Android 基础设施。您可以按照升级 1.12 之前的 Android 项目迁移指南来执行此操作。如果不这样做可能会导致意外的行为。

AndroidX 安卓X

The geolocator plugin requires the AndroidX version of the Android Support Libraries. This means you need to make sure your Android project supports AndroidX. Detailed instructions can be found here.
地理定位器插件需要 AndroidX 版本的 Android 支持库。这意味着您需要确保您的 Android 项目支持 AndroidX。详细说明可以在这里找到。

The TL;DR version is:
TL;DR 版本是:

  1. Add the following to your "gradle.properties" file:
    将以下内容添加到“gradle.properties”文件中:
android.useAndroidX=true
android.enableJetifier=true
copied to clipboard
  1. Make sure you set the compileSdkVersion in your "android/app/build.gradle" file to 33:
    确保将“android/app/build.gradle”文件中的 compileSdkVersion 设置为 33:
android {
  compileSdkVersion 33

  ...
}
copied to clipboard
  1. Make sure you replace all the android. dependencies to their AndroidX counterparts (a full list can be found here: Migrating to AndroidX).
    确保将所有 android. 依赖项替换为其 AndroidX 对应项(完整列表可在此处找到:迁移到 AndroidX)。

Permissions 权限

On Android you'll need to add either the ACCESS_COARSE_LOCATION or the ACCESS_FINE_LOCATION permission to your Android Manifest. To do so open the AndroidManifest.xml file (located under android/app/src/main) and add one of the following two lines as direct children of the <manifest> tag (when you configure both permissions the ACCESS_FINE_LOCATION will be used by the geolocator plugin):
在 Android 上,您需要将 ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION 权限添加到 Android 清单中。为此,请打开 AndroidManifest.xml 文件(位于 android/app/src/main 下),然后添加以下两行之一作为 <manifest> 标记的直接子级(当您配置两个权限时, ACCESS_FINE_LOCATION 将由地理定位器插件使用):

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

Starting from Android 10 you need to add the ACCESS_BACKGROUND_LOCATION permission (next to the ACCESS_COARSE_LOCATION or the ACCESS_FINE_LOCATION permission) if you want to continue receiving updates even when your App is running in the background (note that the geolocator plugin doesn't support receiving and processing location updates while running in the background):
从 Android 10 开始,如果您想继续接收更新,即使您的应用程序已更新,您也需要添加 ACCESS_BACKGROUND_LOCATION 权限(位于 ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION 权限旁边)在后台运行(请注意,地理定位器插件不支持在后台运行时接收和处理位置更新):

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
copied to clipboard

NOTE: Specifying the ACCESS_COARSE_LOCATION permission results in location updates with an accuracy approximately equivalent to a city block. It might take a long time (minutes) before you will get your first locations fix as ACCESS_COARSE_LOCATION will only use the network services to calculate the position of the device. More information can be found here.
注意:指定 ACCESS_COARSE_LOCATION 权限会导致位置更新的精度大约相当于城市街区。您可能需要很长时间(几分钟)才能获得第一个位置修复,因为 ACCESS_COARSE_LOCATION 将仅使用网络服务来计算设备的位置。更多信息可以在这里找到。

iOS

On iOS you'll need to add the following entry to your Info.plist file (located under ios/Runner) in order to access the device's location. Simply open your Info.plist file and add the following (make sure you update the description so it is meaningfull in the context of your App):
在 iOS 上,您需要将以下条目添加到 Info.plist 文件(位于 ios/Runner 下)才能访问设备的位置。只需打开 Info.plist 文件并添加以下内容(确保更新说明,使其在您的应用程序上下文中有意义):

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
copied to clipboard

If you don't need to receive updates when your app is in the background, then add a compiler flag as follows: in XCode, click on Pods, choose the Target 'geolocator_apple', choose Build Settings, in the search box look for 'Preprocessor Macros' then add the BYPASS_PERMISSION_LOCATION_ALWAYS=1 flag. Setting this flag prevents your app from requiring the NSLocationAlwaysAndWhenInUseUsageDescription entry in Info.plist, and avoids questions from Apple when submitting your app.
如果您的应用程序在后台时不需要接收更新,请添加编译器标志,如下所示:在 XCode 中,单击 Pods,选择目标“geolocator_apple”,选择“构建设置”,在搜索框中查找“然后,预处理器宏添加 BYPASS_PERMISSION_LOCATION_ALWAYS=1 标志。设置此标志可防止您的应用程序需要 Info.plist 中的 NSLocationAlwaysAndWhenInUseUsageDescription 条目,并避免在提交应用程序时 Apple 提出问题。

You can also have the flag set automatically by adding the following to the ios/Podfile of your application:
您还可以通过将以下内容添加到应用程序的 ios/Podfile 来自动设置标志:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "geolocator_apple"
      target.build_configurations.each do |config|
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'BYPASS_PERMISSION_LOCATION_ALWAYS=1']
      end
    end
  end
end
copied to clipboard

If you do want to receive updates when your App is in the background (or if you don't bypass the permission request as described above) then you'll need to:
如果您确实希望在应用程序处于后台时接收更新(或者如果您不按照上述方式绕过权限请求),那么您需要:

  • Add the Background Modes capability to your XCode project (Project > Signing and Capabilities > "+ Capability" button) and select Location Updates. Be careful with this, you will need to explain in detail to Apple why your App needs this when submitting your App to the AppStore. If Apple isn't satisfied with the explanation your App will be rejected.
    将后台模式功能添加到您的 XCode 项目(项目 > 签名和功能 >“+ 功能”按钮)并选择位置更新。请小心这一点,在将您的应用程序提交到AppStore时,您需要向Apple详细解释为什么您的应用程序需要这个。如果 Apple 对解释不满意,您的应用程序将被拒绝。
  • Add an NSLocationAlwaysAndWhenInUseUsageDescription entry to your Info.plist (use NSLocationAlwaysUsageDescription if you're targeting iOS <11.0)
    NSLocationAlwaysAndWhenInUseUsageDescription 条目添加到您的 Info.plist(如果您的目标平台是 iOS <11.0,请使用 NSLocationAlwaysUsageDescription

When using the requestTemporaryFullAccuracy({purposeKey: "YourPurposeKey"}) method, a dictionary should be added to the Info.plist file.
使用 requestTemporaryFullAccuracy({purposeKey: "YourPurposeKey"}) 方法时,应将字典添加到Info.plist文件中。

<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
  <key>YourPurposeKey</key>
  <string>The example App requires temporary access to the device&apos;s precise location.</string>
</dict>
copied to clipboard

The second key (in this example called YourPurposeKey) should match the purposeKey that is passed in the requestTemporaryFullAccuracy() method. It is possible to define multiple keys for different features in your app. More information can be found in Apple's documentation.
第二个键(在此示例中称为 YourPurposeKey )应与 requestTemporaryFullAccuracy() 方法中传递的 PurposeKey 匹配。可以为应用程序中的不同功能定义多个键。更多信息可以在 Apple 的文档中找到。

NOTE: the first time requesting temporary full accuracy access it might take several seconds for the pop-up to show. This is due to the fact that iOS is determining the exact user location which may take several seconds. Unfortunately this is out of our hands.

macOS 苹果系统

On macOS you'll need to add the following entries to your Info.plist file (located under macOS/Runner) in order to access the device's location. Simply open your Info.plist file and add the following (make sure you update the description so it is meaningfull in the context of your App):

<key>NSLocationUsageDescription</key>
<string>This app needs access to location.</string>
copied to clipboard

You will also have to add the following entry to the DebugProfile.entitlements and Release.entitlements files. This will declare that your App wants to make use of the device's location services and adds it to the list in the "System Preferences" -> "Security & Privace" -> "Privacy" settings.

<key>com.apple.security.personal-information.location</key>
<true/>
copied to clipboard

When using the requestTemporaryFullAccuracy({purposeKey: "YourPurposeKey"}) method, a dictionary should be added to the Info.plist file.

<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
  <key>YourPurposeKey</key>
  <string>The example App requires temporary access to the device&apos;s precise location.</string>
</dict>
copied to clipboard

The second key (in this example called YourPurposeKey) should match the purposeKey that is passed in the requestTemporaryFullAccuracy() method. It is possible to define multiple keys for different features in your app. More information can be found in Apple's documentation.

NOTE: the first time requesting temporary full accuracy access it might take several seconds for the pop-up to show. This is due to the fact that macOS is determining the exact user location which may take several seconds. Unfortunately this is out of our hands.

Web

To use the Geolocator plugin on the web you need to be using Flutter 1.20 or higher. Flutter will automatically add the endorsed geolocator_web package to your application when you add the geolocator: ^6.2.0 dependency to your pubspec.yaml.

The following methods of the geolocator API are not supported on the web and will result in a UnsupportedError:

  • getLastKnownPosition({ bool forceAndroidLocationManager = true })
  • openAppSettings()
  • openLocationSettings()
  • getServiceStatusStream()

NOTE

Geolocator Web is available only in secure_contexts (HTTPS). More info about the Geolocator API can be found here.

Windows 视窗

To use the Geolocator plugin on Windows you need to be using Flutter 2.10 or higher. Flutter will automatically add the endorsed geolocator_windows package to your application when you add the geolocator: ^8.1.0 dependency to your pubspec.yaml.

Example # 例子 #

The code below shows an example on how to acquire the current position of the device, including checking if the location services are enabled and checking / requesting permission to access the position of the device:
下面的代码显示了如何获取设备当前位置的示例,包括检查位置服务是否启用以及检查/请求访问设备位置的权限:

import 'package:geolocator/geolocator.dart';

/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
  bool serviceEnabled;
  LocationPermission permission;

  // Test if location services are enabled.
  serviceEnabled = await Geolocator.isLocationServiceEnabled();
  if (!serviceEnabled) {
    // Location services are not enabled don't continue
    // accessing the position and request users of the 
    // App to enable the location services.
    return Future.error('Location services are disabled.');
  }

  permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
      // Permissions are denied, next time you could try
      // requesting permissions again (this is also where
      // Android's shouldShowRequestPermissionRationale 
      // returned true. According to Android guidelines
      // your App should show an explanatory UI now.
      return Future.error('Location permissions are denied');
    }
  }
  
  if (permission == LocationPermission.deniedForever) {
    // Permissions are denied forever, handle appropriately. 
    return Future.error(
      'Location permissions are permanently denied, we cannot request permissions.');
  } 

  // When we reach here, permissions are granted and we can
  // continue accessing the position of the device.
  return await Geolocator.getCurrentPosition();
}
copied to clipboard

API # API#

Geolocation # 地理位置#

Current location 当前位置

To query the current location of the device simply make a call to the getCurrentPosition method. You can finetune the results by specifying the following parameters:
要查询设备的当前位置,只需调用 getCurrentPosition 方法即可。您可以通过指定以下参数来微调结果:

  • desiredAccuracy: the accuracy of the location data that your app wants to receive;
    desiredAccuracy :您的应用想要接收的位置数据的准确性;
  • timeLimit: the maximum amount of time allowed to acquire the current location. When the time limit is passed a TimeOutException will be thrown and the call will be cancelled. By default no limit is configured.
    timeLimit :允许获取当前位置的最长时间。当超过时间限制时,将抛出 TimeOutException 并取消调用。默认情况下没有配置限制。
import 'package:geolocator/geolocator.dart';

Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
copied to clipboard

Last known location 最后已知位置

To query the last known location retrieved stored on the device you can use the getLastKnownPosition method (note that this can result in a null value when no location details are available):
要查询设备上存储的最后检索到的已知位置,您可以使用 getLastKnownPosition 方法(请注意,当没有位置详细信息可用时,这可能会导致 null 值):

import 'package:geolocator/geolocator.dart';

Position? position = await Geolocator.getLastKnownPosition();
copied to clipboard

Listen to location updates
收听位置更新

To listen for location changes you can call the getPositionStream to receive stream you can listen to and receive position updates. You can finetune the results by specifying the following parameters:
要监听位置更改,您可以调用 getPositionStream 来接收流,您可以监听并接收位置更新。您可以通过指定以下参数来微调结果:

  • accuracy: the accuracy of the location data that your app wants to receive;
    accuracy :您的应用想要接收的位置数据的准确性;
  • distanceFilter: the minimum distance (measured in meters) a device must move horizontally before an update event is generated;
    distanceFilter :设备在生成更新事件之前必须水平移动的最小距离(以米为单位);
  • timeLimit: the maximum amount of time allowed between location updates. When the time limit is passed a TimeOutException will be thrown and the stream will be cancelled. By default no limit is configured.
    timeLimit :位置更新之间允许的最长时间。当超过时间限制时,将抛出 TimeOutException 并且流将被取消。默认情况下没有配置限制。
import 'package:geolocator/geolocator.dart';

final LocationSettings locationSettings = LocationSettings(
  accuracy: LocationAccuracy.high,
  distanceFilter: 100,
);
StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position? position) {
        print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
    });
copied to clipboard

In certain situation it is necessary to specify some platform specific settings. This can be accomplished using the platform specific AndroidSettings or AppleSettings classes. When using a platform specific class, the platform specific package must be imported as well. For example:
在某些情况下,有必要指定一些特定于平台的设置。这可以使用特定于平台的 AndroidSettingsAppleSettings 类来完成。当使用特定于平台的类时,还必须导入特定于平台的包。例如:

import 'package:geolocator/geolocator.dart';
import 'package:geolocator_apple/geolocator_apple.dart';
import 'package:geolocator_android/geolocator_android.dart';

late LocationSettings locationSettings;

if (defaultTargetPlatform == TargetPlatform.android) {
  locationSettings = AndroidSettings(
    accuracy: LocationAccuracy.high,
    distanceFilter: 100,
    forceLocationManager: true,
    intervalDuration: const Duration(seconds: 10),
    //(Optional) Set foreground notification config to keep the app alive 
    //when going to the background
    foregroundNotificationConfig: const ForegroundNotificationConfig(
        notificationText:
        "Example app will continue to receive your location even when you aren't using it",
        notificationTitle: "Running in Background",
        enableWakeLock: true,
    )
  );
} else if (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS) {
  locationSettings = AppleSettings(
    accuracy: LocationAccuracy.high,
    activityType: ActivityType.fitness,
    distanceFilter: 100,
    pauseLocationUpdatesAutomatically: true,
    // Only set to true if our app will be started up in the background.
    showBackgroundLocationIndicator: false,
  );
} else {
    locationSettings = LocationSettings(
    accuracy: LocationAccuracy.high,
    distanceFilter: 100,
  );
}

StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position? position) {
        print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
    });
copied to clipboard

Location accuracy (Android and iOS 14+ only)
位置准确性(仅限 Android 和 iOS 14+)

To query if a user enabled Approximate location fetching or Precise location fetching, you can call the Geolocator().getLocationAccuracy() method. This will return a Future<LocationAccuracyStatus>, which when completed contains a LocationAccuracyStatus.reduced if the user has enabled Approximate location fetching or LocationAccuracyStatus.precise if the user has enabled Precise location fetching. When calling getLocationAccuracy before the user has given permission, the method will return LocationAccuracyStatus.reduced by default. On iOS 13 or below, the method getLocationAccuracy will always return LocationAccuracyStatus.precise, since that is the default value for iOS 13 and below.
要查询用户是否启用了近似位置获取或精确位置获取,您可以调用 Geolocator().getLocationAccuracy() 方法。这将返回 Future<LocationAccuracyStatus> ,如果用户启用了近似位置获取,则完成后包含 LocationAccuracyStatus.reduced ;如果用户启用了精确位置获取,则包含 LocationAccuracyStatus.precise 。在用户授予权限之前调用 getLocationAccuracy 时,该方法将默认返回 LocationAccuracyStatus.reduced 。在 iOS 13 或更低版本上,方法 getLocationAccuracy 将始终返回 LocationAccuracyStatus.precise ,因为这是 iOS 13 及更低版本的默认值。

import 'package:geolocator/geolocator.dart';

var accuracy = await Geolocator.getLocationAccuracy();
copied to clipboard

Location service information
位置服务信息

To check if location services are enabled you can call the isLocationServiceEnabled method:
要检查位置服务是否已启用,您可以调用 isLocationServiceEnabled 方法:

import 'package:geolocator/geolocator.dart';

bool isLocationServiceEnabled  = await Geolocator.isLocationServiceEnabled();
copied to clipboard

To listen for service status changes you can call the getServiceStatusStream. This will return a Stream<ServiceStatus> which can be listened to, to receive location service status updates.
要侦听服务状态更改,您可以调用 getServiceStatusStream 。这将返回一个可以监听的 Stream<ServiceStatus> ,以接收位置服务状态更新。

import 'package:geolocator/geolocator.dart';

StreamSubscription<ServiceStatus> serviceStatusStream = Geolocator.getServiceStatusStream().listen(
    (ServiceStatus status) {
        print(status);
    });
copied to clipboard

Permissions # 权限#

When using the web platform, the checkPermission method will return the LocationPermission.denied status, when the browser doesn't support the JavaScript Permissions API. Nevertheless, the getCurrentPosition and getPositionStream methods can still be used on the web platform.
使用网络平台时,如果浏览器不支持 JavaScript Permissions API, checkPermission 方法将返回 LocationPermission.denied 状态。尽管如此, getCurrentPositiongetPositionStream 方法仍然可以在Web平台上使用。

If you want to check if the user already granted permissions to acquire the device's location you can make a call to the checkPermission method:
如果您想检查用户是否已授予获取设备位置的权限,您可以调用 checkPermission 方法:

import 'package:geolocator/geolocator.dart';

LocationPermission permission = await Geolocator.checkPermission();
copied to clipboard

If you want to request permission to access the device's location you can call the requestPermission method:
如果您想请求访问设备位置的权限,您可以调用 requestPermission 方法:

import 'package:geolocator/geolocator.dart';

LocationPermission permission = await Geolocator.requestPermission();
copied to clipboard

Possible results from the checkPermission and requestPermission methods are:
checkPermissionrequestPermission 方法的可能结果是:

Permission Description
denied Permission to access the device's location is denied by the user. You are free to request permission again (this is also the initial permission state).
用户拒绝访问设备位置的权限。您可以再次请求权限(这也是初始权限状态)。
deniedForever Permission to access the device's location is permanently denied. When requesting permissions the permission dialog will not be shown until the user updates the permission in the App settings.
访问设备位置的权限被永久拒绝。请求权限时,除非用户在应用程序设置中更新权限,否则不会显示权限对话框。
whileInUse Permission to access the device's location is allowed only while the App is in use.
仅当应用程序正在使用时才允许访问设备的位置。
always Permission to access the device's location is allowed even when the App is running in the background.
即使应用程序在后台运行,也允许访问设备的位置。

Note: Android can only return whileInUse, always or denied when checking permissions. Due to limitations on the Android OS it is not possible to determine if permissions are denied permanently when checking permissions. Using a workaround the geolocator is only able to do so as a result of the requestPermission method. More information can be found in our wiki.
注意:Android 在检查权限时只能返回 whileInUsealwaysdenied 。由于 Android 操作系统的限制,在检查权限时无法确定权限是否被永久拒绝。使用解决方法,地理定位器只能通过 requestPermission 方法来执行此操作。更多信息可以在我们的维基百科中找到。

Settings # 设置 #

In some cases it is necessary to ask the user and update their device settings. For example when the user initially permanently denied permissions to access the device's location or if the location services are not enabled (and, on Android, automatic resolution didn't work). In these cases you can use the openAppSettings or openLocationSettings methods to immediately redirect the user to the device's settings page.
在某些情况下,有必要询问用户并更新他们的设备设置。例如,当用户最初永久拒绝访问设备位置的权限或未启用位置服务(并且在 Android 上,自动解析不起作用)时。在这些情况下,您可以使用 openAppSettingsopenLocationSettings 方法立即将用户重定向到设备的设置页面。

On Android the openAppSettings method will redirect the user to the App specific settings where the user can update necessary permissions. The openLocationSettings method will redirect the user to the location settings where the user can enable/ disable the location services.
在 Android 上, openAppSettings 方法会将用户重定向到应用程序特定设置,用户可以在其中更新必要的权限。 openLocationSettings 方法会将用户重定向到位置设置,用户可以在其中启用/禁用位置服务。

On iOS we are not allowed to open specific setting pages so both methods will redirect the user to the Settings App from where the user can navigate to the correct settings category to update permissions or enable/ disable the location services.
在 iOS 上,我们不允许打开特定的设置页面,因此这两种方法都会将用户重定向到“设置”应用程序,用户可以在其中导航到正确的设置类别以更新权限或启用/禁用位置服务。

import 'package:geolocator/geolocator.dart';

await Geolocator.openAppSettings();
await Geolocator.openLocationSettings();
copied to clipboard

Utility methods # 实用方法#

To calculate the distance (in meters) between two geocoordinates you can use the distanceBetween method. The distanceBetween method takes four parameters:
要计算两个地理坐标之间的距离(以米为单位),您可以使用 distanceBetween 方法。 distanceBetween 方法有四个参数:

Parameter Type Description
startLatitude double Latitude of the start position
起始位置的纬度
startLongitude double Longitude of the start position
起始位置的经度
endLatitude double Latitude of the destination position
目的地位置的纬度
endLongitude double Longitude of the destination position
目的地位置的经度
import 'package:geolocator/geolocator.dart';

double distanceInMeters = Geolocator.distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);
copied to clipboard

If you want to calculate the bearing between two geocoordinates you can use the bearingBetween method. The bearingBetween method also takes four parameters:
如果要计算两个地理坐标之间的方位角,可以使用 bearingBetween 方法。 bearingBetween 方法还采用四个参数:

Parameter Type Description
startLatitude double Latitude of the start position
起始位置的纬度
startLongitude double Longitude of the start position
起始位置的经度
endLatitude double Latitude of the destination position
目的地位置的纬度
endLongitude double Longitude of the destination position
目的地位置的经度
import 'package:geolocator/geolocator.dart';

double bearing = Geolocator.bearingBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838);
copied to clipboard

Location accuracy # 定位精度#

Android 安卓

On Android, the LocationAccuracy enum controls the accuracy of the location data the app wants to receive. It also provides control over the priority given to the location stream. This can be confusing, as a priority of lowest might not return any location, while one might expect it to give the quickest responses. The table below outlines the priority and its meaning per accuracy option:
在 Android 上, LocationAccuracy 枚举控制应用想要接收的位置数据的准确性。它还提供对位置流优先级的控制。这可能会令人困惑,因为最低优先级可能不会返回任何位置,而人们可能期望它给出最快的响应。下表概述了每个精度选项的优先级及其含义:

Location accuracy 定位精度 Android priority 安卓优先 Description
lowest PRIORITY_PASSIVE Ensures that no extra power will be used to derive locations. This enforces that the request will act as a passive listener that will only receive "free" locations calculated on behalf of other clients, and no locations will be calculated on behalf of only this request.
确保不会使用额外的电力来获取位置。这强制请求将充当被动侦听器,仅接收代表其他客户端计算的“免费”位置,并且不会仅代表此请求计算任何位置。
low PRIORITY_LOW_POWER Requests a tradeoff that favors low power usage at the possible expense of location accuracy.
要求进行权衡,有利于低功耗,但可能会牺牲位置精度。
medium PRIORITY_BALANCED_POWER_ACCURACY Requests a tradeoff that is balanced between location accuracy and power usage.
要求在位置精度和功耗之间进行权衡。
high+ 高+ PRIORITY_HIGH_ACCURACY Requests a tradeoff that favors highly accurate locations at the possible expense of additional power usage.
要求进行权衡,以支持高精度位置,但可能会消耗额外的电量。

iOS

On iOS, the LocationAccuracy enum controls the accuracy of the location data the app wants to receive. It also provides control on the battery consumption of the device: the more detailed data is requested, the larger the impact on the battery consumption. More details can be found on Apple's documentation. The table below shows how the LocationAccuracy values map to the native iOS accuracy settings.
在 iOS 上, LocationAccuracy 枚举控制应用程序想要接收的位置数据的准确性。它还提供对设备电池消耗的控制:请求的数据越详细,对电池消耗的影响就越大。更多详细信息可以在 Apple 的文档中找到。下表显示了 LocationAccuracy 值如何映射到本机 iOS 准确度设置。

Location accuracy 定位精度 iOS accuracy iOS 准确度 Description
lowest kCLLocationAccuracyThreeKilometers Accurate to the nearest three kilometers.
精确到最近的三公里。
low kCLLocationAccuracyKilometer Accurate to the nearest kilometer.
精确到最近的公里。
medium kCLLocationAccuracyHundredMeters Accurate to within one hundred meters.
精确到百米以内。
high kCLLocationAccuracyNearestTenMeters Accurate to within ten meters of the desired target.
精确到所需目标十米以内。
best kCLLocationAccuracyBest The best level of accuracy available.
可用的最佳准确度水平。
bestForNavigation kCLLocationAccuracyBestForNavigation The highest possible accuracy that uses additional sensor data to facilitate navigation apps.
使用额外的传感器数据来促进导航应用程序的尽可能高的精度。

Issues # 问题 #

Please file any issues, bugs or feature requests as an issue on our GitHub page. Commercial support is available, you can contact us at hello@baseflow.com.
请将任何问题、错误或功能请求作为问题提交到我们的 GitHub 页面上。提供商业支持,您可以通过 hello@baseflow.com 联系我们。

Want to contribute # 想要贡献#

If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please carefully review our contribution guide and send us your pull request.
如果您想为插件做出贡献(例如,通过改进文档、解决错误或添加很酷的新功能),请仔细查看我们的贡献指南并向我们发送您的拉取请求。

Author # 作者 #

This Geolocator plugin for Flutter is developed by Baseflow.
Flutter 的 Geolocator 插件由 Baseflow 开发。

5084
likes
140
pub points
100%
popularity

Publisher

verified publisherbaseflow.com

Geolocation plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API for generic location (GPS etc.) functions.

Repository (GitHub)
View/report issues
Contributing

Documentation

API reference

License

MIT (LICENSE)

Dependencies

flutter, geolocator_android, geolocator_apple, geolocator_platform_interface, geolocator_web, geolocator_windows

More

Packages that depend on geolocator