Flutter谷歌地图网络服务插件google_maps_webservice2的使用

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

Flutter谷歌地图网络服务插件google_maps_webservice2的使用

1. 引言

本篇文档将详细介绍如何在Flutter项目中使用google_maps_webservice2插件。该库提供了与Google Maps Web Services进行交互的功能。

2. 一般信息

google_maps_webservice2是一个用于Google Maps Web Services的Dart库。你可以在这里找到Google Maps平台文档,但如果你是新手,建议从这里开始了解。

3. API密钥

要使用此库,你需要一个Web API密钥。请按照这些步骤获取适用于你的Dart应用的相关密钥。这些密钥不应作为Android或iOS API密钥单独使用,而是应该在你的Dart应用中使用。

4. 可用API

  • ✅ 地理编码
  • ❌ 地点
    • ✅ 附近搜索
    • ✅ 文本搜索
    • ✅ 详情
    • ❌ 添加
    • ❌ 删除
    • ✅ 图片
    • ✅ 自动完成
    • ✅ 查询自动完成
  • ✅ 路线
  • ✅ 距离矩阵
  • ❌ 定位
  • ❌ 海拔
  • ❌ 道路
  • ✅ 时区
  • ✅ 静态地图

5. 使用方法

5.1 地理编码
import 'package:google_maps_webservice/geocoding.dart';

final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>");
final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>", httpClient: BrowserClient());
final geocoding = GoogleMapsGeocoding(baseUrl: "http://myProxy.com");

GeocodingResponse response = await geocoding.searchByAddress("1600 Amphitheatre Parkway, Mountain View, CA");
5.2 地点
import 'package:google_maps_webservice/places.dart';

final places = GoogleMapsPlaces(apiKey: "<API_KEY>");
final places = GoogleMapsPlaces(apiKey: "<API_KEY>", httpClient: BrowserClient());
final places = GoogleMapsPlaces(baseUrl: "http://myProxy.com");

PlacesSearchResponse response = await places.searchNearbyWithRadius(Location(lat: 31.0424, lng: 42.421), 500);
PlacesSearchResponse response = await places.searchNearbyWithRankby(Location(lat: 31.0424, lng: 42.421), "distance");
PlacesSearchResponse response = await places.searchByText("123 Main Street");

PlacesDetailsResponse response = await places.getDetailsByPlaceId("PLACE_ID");
PlacesDetailsResponse response = await places.getDetailsByReference("REF");
5.3 时区
import 'package:google_maps_webservice/timezone.dart';

final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>");
final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>", httpClient: BrowserClient());
final timezone = GoogleMapsTimezone(baseUrl: "http://myProxy.com");

TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421));
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24));
TimezoneResponse response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421), timestamp: DateTime.utc(2019, 4, 24), language: 'es');
5.4 静态地图
import 'package:google_maps_webservice/static_map.dart';

// 初始化静态地图对象
StaticMap mapStatic = StaticMap(
  apiKey,
  markers: List.from([
    Location(lat: 23.721160, lng: 90.394435),
    Location(lat: 23.732322, lng: 90.385142),]
  ),
  path: Path(
    enc: 'svh~F`j}uOusC`bD',
    color: 'black',
  ),
  scale: 'false'
);

// 获取静态地图URL
String url = mapStatic.getUrl();

// 显示静态地图
Image.network(url)

更多关于Flutter谷歌地图网络服务插件google_maps_webservice2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter谷歌地图网络服务插件google_maps_webservice2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用google_maps_webservice2插件来获取谷歌地图网络服务(如地址解析和地理编码)的示例代码。这个插件允许你访问谷歌地图的各种网络服务,例如地理编码(Geocoding)和反向地理编码(Reverse Geocoding)。

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

dependencies:
  flutter:
    sdk: flutter
  google_maps_webservice2: ^2.0.10  # 请确保使用最新版本

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

接下来,你可以在你的Flutter项目中编写代码来使用这个插件。以下是一个简单的示例,展示如何执行地理编码和反向地理编码:

import 'package:flutter/material.dart';
import 'package:google_maps_webservice2/places.dart';
import 'package:google_maps_webservice2/geocoding.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Google Maps Webservice Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final GeocodingApi _geocodingApi = GeocodingApi();
  final PlacesApi _placesApi = PlacesApi();

  String _address = '';
  String _latLng = '';

  Future<void> _geocodeAddress(String address) async {
    try {
      var response = await _geocodingApi.geocode(address);
      if (response.results.isNotEmpty) {
        var latLng = response.results.first.geometry.location;
        setState(() {
          _latLng = "${latLng.lat}, ${latLng.lng}";
        });
      } else {
        setState(() {
          _latLng = 'Address not found';
        });
      }
    } catch (e) {
      setState(() {
        _latLng = 'Error: ${e.message}';
      });
    }
  }

  Future<void> _reverseGeocodeLatLng(String latLng) async {
    try {
      var coords = latLng.split(',').map(double.parse).toList();
      var response = await _geocodingApi.reverseGeocode(coords[0], coords[1]);
      if (response.results.isNotEmpty) {
        var address = response.results.first.formattedAddress;
        setState(() {
          _address = address;
        });
      } else {
        setState(() {
          _address = 'Location not found';
        });
      }
    } catch (e) {
      setState(() {
        _address = 'Error: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Google Maps Webservice Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              decoration: InputDecoration(labelText: 'Address'),
              onSubmitted: (address) => _geocodeAddress(address),
            ),
            SizedBox(height: 16),
            Text('Latitude, Longitude: $_latLng'),
            SizedBox(height: 32),
            TextField(
              decoration: InputDecoration(labelText: 'Latitude, Longitude'),
              onSubmitted: (latLng) => _reverseGeocodeLatLng(latLng),
            ),
            SizedBox(height: 16),
            Text('Address: $_address'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们有两个主要的功能:

  1. _geocodeAddress(String address):将地址转换为经纬度。
  2. _reverseGeocodeLatLng(String latLng):将经纬度转换为地址。

注意:

  • 你需要为你的Google Maps API服务启用相应的API,并获取一个API密钥。
  • 你需要在插件的初始化过程中提供这个API密钥,例如通过GeocodingApi.apiKey = 'YOUR_API_KEY';

由于google_maps_webservice2插件的API可能会随时间变化,请参考最新的插件文档和API参考以获取最新的使用方法和最佳实践。

回到顶部