Flutter地理编码插件google_geocoding_api的使用

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

Flutter地理编码插件google_geocoding_api的使用

Introduction

google_geocoding_api 是一个实现Google Geocoding API的Dart包(不依赖Flutter)。在使用该包之前,请确保阅读开始前并在Google开发者控制台创建API密钥。

Pub License: MIT

Buy Me A Coffee


Usage

Geocoding (latitude/longitude lookup)

下面是一个如何使用Geocoding搜索的例子。请先阅读Geocoding (latitude/longitude lookup)

import 'package:google_geocoding_api/google_geocoding_api.dart';

Future<void> main() async {
  const String googleApiKey = 'YOUR_API_KEY';
  final bool isDebugMode = true;  
  final api = GoogleGeocodingApi(googleApiKey, isLogged: isDebugMode);  
  final searchResults = await api.search(
    'Boston',
    language: 'en',
  );
  print(searchResults);
}

Reverse geocoding (address lookup)

下面是如何使用反向地理编码(地址查找)的例子。请先阅读Reverse geocoding (address lookup)

import 'package:google_geocoding_api/google_geocoding_api.dart';

Future<void> main() async {
  const String googleApiKey = 'YOUR_API_KEY';
  final bool isDebugMode = true;  
  final api = GoogleGeocodingApi(googleApiKey, isLogged: isDebugMode);  
  final reversedSearchResults = await api.reverse(
    '42.360083,-71.05888',
    language: 'en',
  );
  print(reversedSearchResults);
}

Place geocoding

下面是如何使用地点地理编码的例子。请先阅读Place Geocoding

import 'package:google_geocoding_api/google_geocoding_api.dart';

Future<void> main() async {
  const String googleApiKey = 'YOUR_API_KEY';
  final bool isDebugMode = true;  
  final api = GoogleGeocodingApi(googleApiKey, isLogged: isDebugMode);  
  final placeSearchResults = await api.placeGeocoding(
    'ChIJd8BlQ2BZwokRAFUEcm_qrcA',
    language: 'en',
  );
  print(placeSearchResults);
}

Pretty Address

现在你可以使用.mapToPretty()来获取一个GeocodingPrettyAddress实例,包含addresscitycountrylatitudelongitudepostalCodestatecountryCodestreetNumberstreetNameplaceId等信息。

注意: 该功能是实验性的,可能不能完全满足你的需求。任何改进建议都可以写在Issue Tracker中。

final placeSearchResults = await api.placeGeocoding(
  'ChIJd8BlQ2BZwokRAFUEcm_qrcA',
  language: 'en',
);

final prettyAddress = placeSearchResults.results.firstOrNull?.mapToPretty();

if (prettyAddress == null) {
  return null;
}

print(prettyAddress.postalCode);
print(prettyAddress.streetNumber);
print(prettyAddress.streetName);
print(prettyAddress.city);
print(prettyAddress.state);
print(prettyAddress.placeId);
print(prettyAddress.country);
print(prettyAddress.address);
print(prettyAddress.countryCode);
print(prettyAddress.latitude);
print(prettyAddress.longitude);

Contact and bugs

有任何问题或bug报告,请使用Issue Tracker

示例代码

以下是一个完整的示例代码,包含了正向地理编码、反向地理编码以及地点地理编码的功能:

import 'package:google_geocoding_api/google_geocoding_api.dart';

Future<void> main() async {
  const String googleApiKey = 'YOUR_API_KEY';
  final bool isDebugMode = true;
  final api = GoogleGeocodingApi(googleApiKey, isLogged: isDebugMode);

  // 正向地理编码
  final searchResults = await api.search('Boston', language: 'uk');
  print('正向地理编码结果:');
  for (var res in searchResults.results) {
    print(res.mapToPretty());
  }

  // 反向地理编码
  final reversedSearchResults = await api.reverse(
    '42.360083,-71.05888',
    language: 'en',
  );
  print('反向地理编码结果:');
  for (var res in reversedSearchResults.results) {
    print(res.mapToPretty());
  }

  // 地点地理编码
  final placeSearchResults = await api.placeGeocoding(
    'ChIJd8BlQ2BZwokRAFUEcm_qrcA',
    language: 'en',
  );
  print('地点地理编码结果:');
  for (var res in placeSearchResults.results) {
    print(res.mapToPretty());
  }

  // 打印Pretty Address信息
  final prettyAddress = placeSearchResults.results.firstOrNull?.mapToPretty();
  if (prettyAddress != null) {
    print('Pretty Address信息:');
    print(prettyAddress.postalCode);
    print(prettyAddress.streetNumber);
    print(prettyAddress.streetName);
    print(prettyAddress.city);
    print(prettyAddress.state);
    print(prettyAddress.stateCode);
    print(prettyAddress.placeId);
    print(prettyAddress.country);
    print(prettyAddress.address);
    print(prettyAddress.countryCode);
    print(prettyAddress.latitude);
    print(prettyAddress.longitude);
  }
}

请根据自己的需求修改API密钥和参数。希望这个指南能帮助你更好地理解和使用google_geocoding_api插件。


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

1 回复

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


当然,下面是一个关于如何使用Flutter地理编码插件google_geocoding_api的示例代码。这个示例展示了如何进行正向地理编码(根据地址获取经纬度)和反向地理编码(根据经纬度获取地址)。

首先,确保你已经在pubspec.yaml文件中添加了google_geocoding_api依赖:

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

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

接下来,创建一个Flutter应用,并在其中使用google_geocoding_api插件。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Google Geocoding API Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GeocodingDemo(),
    );
  }
}

class GeocodingDemo extends StatefulWidget {
  @override
  _GeocodingDemoState createState() => _GeocodingDemoState();
}

class _GeocodingDemoState extends State<GeocodingDemo> {
  String _address = '';
  String _latitude = '';
  String _longitude = '';
  String _result = '';

  final Geocoding _geocoding = Geocoding(apiKey: 'YOUR_GOOGLE_MAPS_API_KEY'); // 请替换为你的Google Maps API Key

  void _performForwardGeocoding() async {
    try {
      List<Placemark> placemarks = await _geocoding.placemarkFromAddress(_address);

      Placemark place = placemarks.isNotEmpty ? placemarks[0] : null;
      if (place != null) {
        setState(() {
          _latitude = place.position.latitude.toString();
          _longitude = place.position.longitude.toString();
          _result = 'Address: ${place.locality}, ${place.postalCode}, ${place.country}';
        });
      }
    } catch (e) {
      setState(() {
        _result = 'Error: $e';
      });
    }
  }

  void _performReverseGeocoding() async {
    try {
      List<Placemark> placemarks = await _geocoding.placemarkFromCoordinates(
        double.parse(_latitude),
        double.parse(_longitude),
      );

      Placemark place = placemarks.isNotEmpty ? placemarks[0] : null;
      if (place != null) {
        setState(() {
          _address = '${place.thoroughfare}, ${place.subThoroughfare}, ${place.locality}, ${place.postalCode}, ${place.country}';
          _result = 'Coordinates: $_latitude, $_longitude\nAddress: $_address';
        });
      }
    } catch (e) {
      setState(() {
        _result = 'Error: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Geocoding API Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Address'),
              onChanged: (value) {
                setState(() {
                  _address = value;
                });
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _address.isNotEmpty ? _performForwardGeocoding : null,
              child: Text('Forward Geocoding'),
            ),
            SizedBox(height: 16),
            TextField(
              decoration: InputDecoration(labelText: 'Latitude'),
              keyboardType: TextInputType.number,
              onChanged: (value) {
                setState(() {
                  _latitude = value;
                });
              },
            ),
            SizedBox(height: 8),
            TextField(
              decoration: InputDecoration(labelText: 'Longitude'),
              keyboardType: TextInputType.number,
              onChanged: (value) {
                setState(() {
                  _longitude = value;
                });
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: (_latitude.isNotEmpty && _longitude.isNotEmpty)
                  ? _performReverseGeocoding
                  : null,
              child: Text('Reverse Geocoding'),
            ),
            SizedBox(height: 24),
            Text(_result, style: TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,用户可以在界面上输入地址或经纬度坐标,然后分别触发正向地理编码和反向地理编码操作。结果会显示在界面的文本区域中。

请注意,你需要将'YOUR_GOOGLE_MAPS_API_KEY'替换为你自己的Google Maps API Key。你可以在Google Cloud Platform上创建一个项目并启用Geocoding API来获取这个Key。

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

回到顶部