Flutter地理定位与地图展示插件geography的使用

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

Flutter地理定位与地图展示插件geography的使用

标题

Flutter地理定位与地图展示插件geography的使用

内容

This is a constant data-as-code library called geography facilitating operations like:

  • Search places by name
  • Find the named place nearest to coordinates
  • Measure distance between places

This scope of this data is best represented as: Earth > [Country] > [Region] > [City]

If you’re looking to use basic locations from the coordinates provided by a device, this library will get you pretty far. If you’re looking for more granularity, like addresses or business names, this library won’t be a great fit for your project.

Features

Search places by name and proximity
import 'package:geography/earth.dart';

void main() {
  var a = Earth().search("Texas, Austin").first;
  var t = Earth().findClosestRegion(a);
  var u = Earth().findClosestCountry(t!);
  print("> ${u.name} @ ${u.latitude}° ${u.longitude}°");
  print("> ${u.name}, ${t.name} @ ${t.latitude}° ${t.longitude}°");
  print("> ${u.name}, ${t.name}, ${a.name} @ ${a.latitude}° ${a.longitude}°");

  /**
   * Prints:
   *
   * > United States @ 38.0° -97.0°
   * > United States, Texas @ 31.9685988° -99.9018131°
   * > United States, Texas, Austin @ 30.26715° -97.74306°
   * Exited
   */
}
Find the named place nearest to coordinates
import 'package:geography/basic.dart';

/// Our own derived class to mark coordinates
class GeoLocation extends GeoCoords {
  GeoLocation(double lat, double long) : super(latitude: lat, longitude: long);

  static GeoLocation get austin => GeoLocation(30.26715, -97.74306);
}

void main() {
  var a = unitedStatesTexas.cities.findClosestTo(GeoLocation.austin)!;
  var t = a.state; // Expected to be `Texas`
  var u = t.country; // Expected to be `United States`
  print("> ${u.name} @ ${u.latitude}° ${u.longitude}°");
  print("> ${t.nameQualified} @ ${t.latitude}° ${t.longitude}°");
  print("> ${a.nameQualified} @ ${a.latitude}° ${a.longitude}°");

  /**
   * Prints:
   *
   * > United States @ 38.0° -97.0°
   * > United States, Texas @ 31.9685988° -99.9018131°
   * > United States, Texas, Austin @ 30.26715° -97.74306°
   * Exited
   */
}
Measure distance between places
import 'package:geography/earth.dart';

main() {
  var a = Earth().search("Texas, Austin").first;
  var s = Earth().search("Texas, San Antonio").first;
  var d = a.distanceFrom(s);

  print("> From ${a.name} to ${s.name} is ${d.toStringAsFixed(2)} meters");

  /**
   * Prints:
   *
   * > From Austin to San Antonio is 118570.24 meters
   * Exited
   */
}
Get timeimezones for a particular country
import 'package:geography/earth.dart';

main() {
  var geoId = GeoCodedIdentity(iso2: 'US');
  var timezones = Earth().timezonesFor(geoId);

  for (var zone in timezones) {
    print('> ${zone.gmtOffsetName} => ${zone.zoneName}');
  }

  /**
   * Prints:
   *
   * > UTC-10:00 => America/Adak
   * > UTC-10:00 => Pacific/Honolulu
   * > UTC-09:00 => America/Anchorage
   * > UTC-09:00 => America/Juneau
   * > UTC-09:00 => America/Metlakatla
   * > UTC-09:00 => America/Nome
   * > UTC-09:00 => America/Sitka
   * > UTC-09:00 => America/Yakutat
   * > UTC-08:00 => America/Los_Angeles
   * > UTC-07:00 => America/Boise
   * > UTC-07:00 => America/Denver
   * > UTC-07:00 => America/Phoenix
   * > UTC-06:00 => America/Chicago
   * > UTC-06:00 => America/Indiana/Knox
   * > UTC-06:00 => America/Indiana/Tell_City
   * > UTC-06:00 => America/Indiana/Menominee
   * > UTC-06:00 => America/North_Dakota/Beulah
   * > UTC-06:00 => America/North_Dakota/Center
   * > UTC-06:00 => America/North_Dakota/New_Salem
   * > UTC-05:00 => America/Detroit
   * > UTC-05:00 => America/Indiana/Indianapolis
   * > UTC-05:00 => America/Indiana/Marengo
   * > UTC-05:00 => America/Indiana/Petersburg
   * > UTC-05:00 => America/Indiana/Vevay
   * > UTC-05:00 => America/Indiana/Vincennes
   * > UTC-05:00 => America/Indiana/Winamac
   * > UTC-05:00 => America/Kentucky/Louisville
   * > UTC-05:00 => America/Kentucky/Monticello
   * > UTC-05:00 => America/New_York
   * Exited
   */
}

Getting started

Start by installing this package via:

dart pub add geography
dependencies:
  geography: ^1.0.0

Usage

import 'package:geography/earth.dart';

main () {
  Earth().search("Texas, Austin").forEach((e) {
    print("> ${e.name} @ ${e.latitude}° ${e.longitude}°");
  });
}

/// Outputs:
/// > Austin @ 30.26715000° -97.74306000°

示例代码

使用基本库

import 'package:geography/basic.dart';

/// 我们自己的坐标标记类
class GeoLocation extends GeoCoords {
  GeoLocation(double lat, double long) : super(latitude: lat, longitude: long);

  static GeoLocation get austin => GeoLocation(30.26715, -97.74306);
}

void main() {
  var a = unitedStatesTexas.cities.findClosestTo(GeoLocation.austin)!;
  var t = a.state; // 预期为 `Texas`
  var u = t.country; // 预期为 `United States`
  print("> ${u.name} @ ${u.latitude}° ${u.longitude}°");
  print("> ${t.nameQualified} @ ${t.latitude}° ${t.longitude}°");
  print("> ${a.nameQualified} @ ${a.latitude}° ${a.longitude}°");

  /**
   * 打印:
   *
   * > United States @ 38.0° -97.0°
   * > United States, Texas @ 31.9685988° -99.9018131°
   * > United States, Texas, Austin @ 30.26715° -97.74306°
   * 结束
   */
}

使用地球库


更多关于Flutter地理定位与地图展示插件geography的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地理定位与地图展示插件geography的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何在Flutter应用中使用地理定位与地图展示插件geolocatorflutter_map的代码示例。尽管你提到了geography插件,但据我所知,geolocatorflutter_map是Flutter社区中较为流行和广泛使用的相关插件。

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

dependencies:
  flutter:
    sdk: flutter
  geolocator: ^9.0.2  # 请检查最新版本号
  flutter_map: ^0.14.0  # 请检查最新版本号
  latlong2: ^0.8.0  # flutter_map 的依赖之一

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

接下来,我们编写一个简单的Flutter应用,展示如何使用这些插件进行地理定位和地图展示。

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong2.dart';
import 'package:flutter_map_marker_popup/flutter_map_marker_popup.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MapScreen(),
    );
  }
}

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  Position? _currentPosition;

  @override
  void initState() {
    super.initState();
    _getCurrentLocation();
  }

  Future<void> _getCurrentLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 测试位置服务是否可用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('位置服务不可用');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('位置权限被拒绝');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error('位置权限被永久拒绝,我们需要用户手动在设置中启用');
    }

    _currentPosition = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('地图展示'),
      ),
      body: _currentPosition == null
          ? Center(child: CircularProgressIndicator())
          : FlutterMap(
              options: MapOptions(
                center: LatLng(_currentPosition!.latitude, _currentPosition!.longitude),
                zoom: 14.0,
              ),
              layers: [
                TileLayerOptions(
                  urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                  subdomains: ['a', 'b', 'c'],
                ),
                MarkerLayerOptions(
                  markers: [
                    Marker(
                      width: 80.0,
                      height: 80.0,
                      point: LatLng(_currentPosition!.latitude, _currentPosition!.longitude),
                      builder: (ctx) => Container(
                        child: Icon(
                          Icons.location_on,
                          color: Colors.red,
                          size: 40.0,
                        ),
                      ),
                      popupBuilder: (BuildContext context) {
                        return MarkerPopup(
                          child: Container(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              '当前位置: $_currentPosition!',
                              style: TextStyle(color: Colors.black),
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ],
            ),
    );
  }
}

在这个示例中,我们做了以下工作:

  1. 使用geolocator插件获取当前位置。
  2. 使用flutter_map插件展示地图,并在地图上标记当前位置。
  3. 添加了一个标记弹出窗口,当用户点击标记时会显示当前位置的详细信息。

注意,flutter_map_marker_popup是一个第三方包,用于在flutter_map上实现标记的弹出窗口功能。如果你不需要这个功能,可以移除相关的依赖和代码。

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

回到顶部