Flutter谷歌地图Web服务插件googlemaps_flutter_webservices的使用
Flutter谷歌地图Web服务插件googlemaps_flutter_webservices的使用
一般信息
这是Google Maps Web服务的Dart库。您可以在这里找到Google Maps平台文档,如果您是初学者,可以先从这里开始。
API密钥
要使用此库,您需要一个Web API密钥。请按照这些步骤获取与您的特定Dart应用程序相关的密钥。
这些密钥不能单独用于Android或iOS API密钥,而是应该在您的Dart应用程序中使用。
可用API
- ✅ 地理编码
- ❌ 地点
- ✅ 附近搜索
- ✅ 文本搜索
- ✅ 详情
- ❌ 添加
- ❌ 删除
- ✅ 图片
- ✅ 自动完成
- ✅ 查询自动完成
- ✅ 方向
- ✅ 距离矩阵
- ❌ 地理定位
- ❌ 海拔
- ❌ 道路
- ✅ 时区
- ✅ 静态地图
使用方法
地理编码
import "package:flutter_google_maps_webservices/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");
地点
import "package:flutter_google_maps_webservices/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");
时区
import "package:flutter_google_maps_webservices/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');
静态地图
import "package:flutter_google_maps_webservices/staticmap.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)
代理
如果使用代理,可以通过设置baseUrl来实现。如果代理设置了apiKey,则apiKey不是必需的。(不在应用中存储apiKey是一个好实践)
功能请求和问题
请在问题跟踪器提交功能请求和问题。
完整示例Demo
以下是一个完整的示例代码,演示如何使用googlemaps_flutter_webservices
插件:
import 'package:flutter/material.dart';
import 'package:flutter_google_maps_webservices/geocoding.dart';
import 'package:flutter_google_maps_webservices/places.dart';
import 'package:flutter_google_maps_webservices/timezone.dart';
import 'package:flutter_google_maps_webservices/staticmap.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
[@override](/user/override)
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String _geocodingResult = '';
String _timezoneResult = '';
String _staticMapUrl = '';
final geocoding = GoogleMapsGeocoding(apiKey: "<API_KEY>");
final timezone = GoogleMapsTimezone(apiKey: "<API_KEY>");
final staticMap = StaticMap("<API_KEY>");
[@override](/user/override)
void initState() {
super.initState();
fetchGeocodingData();
fetchTimezoneData();
fetchStaticMapData();
}
Future<void> fetchGeocodingData() async {
try {
final response = await geocoding.searchByAddress("1600 Amphitheatre Parkway, Mountain View, CA");
setState(() {
_geocodingResult = response.results.first.geometry.location.toString();
});
} catch (e) {
setState(() {
_geocodingResult = e.toString();
});
}
}
Future<void> fetchTimezoneData() async {
try {
final response = await timezone.getByLocation(Location(lat: 31.0424, lng: 42.421));
setState(() {
_timezoneResult = response.timeZoneId;
});
} catch (e) {
setState(() {
_timezoneResult = e.toString();
});
}
}
Future<void> fetchStaticMapData() async {
try {
staticMap.markers = List.from([
Location(lat: 23.721160, lng: 90.394435),
Location(lat: 23.732322, lng: 90.385142),
]);
staticMap.path = Path(
enc: 'svh~F`j}uOusC`bD',
color: 'black',
);
setState(() {
_staticMapUrl = staticMap.getUrl();
});
} catch (e) {
setState(() {
_staticMapUrl = e.toString();
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Maps Web Services Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text('Geocoding Result: $_geocodingResult'),
SizedBox(height: 16),
Text('Timezone Result: $_timezoneResult'),
SizedBox(height: 16),
_staticMapUrl.isNotEmpty
? Image.network(_staticMapUrl)
: CircularProgressIndicator(),
],
),
),
);
}
}
更多关于Flutter谷歌地图Web服务插件googlemaps_flutter_webservices的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter谷歌地图Web服务插件googlemaps_flutter_webservices的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 googlemaps_flutter_webservices
插件在 Flutter 中集成谷歌地图 Web 服务的示例代码。这个插件允许你访问谷歌地图的多个 Web 服务,如地理编码(Geocoding)和反向地理编码(Reverse Geocoding)。
首先,确保你已经在 pubspec.yaml
文件中添加了 googlemaps_flutter_webservices
依赖:
dependencies:
flutter:
sdk: flutter
googlemaps_flutter_webservices: ^0.0.19 # 请检查最新版本号
然后,运行 flutter pub get
来获取依赖。
接下来是一个简单的 Flutter 应用示例,演示如何使用 googlemaps_flutter_webservices
进行地理编码和反向地理编码。
import 'package:flutter/material.dart';
import 'package:googlemaps_flutter_webservices/geocoding.dart';
import 'package:googlemaps_flutter_webservices/places.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Google Maps Web Services Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _geocodingResult = '';
String _reverseGeocodingResult = '';
final Geocoding _geocoding = Geocoding(apiKey: 'YOUR_API_KEY'); // 替换为你的API密钥
void _geocodeAddress() async {
String address = '1600 Amphitheatre Parkway, Mountain View, CA';
GeocodingResponse response = await _geocoding.geocodeAddress(address);
if (response.results.isNotEmpty) {
setState(() {
_geocodingResult = response.results.first.geometry.location.toString();
});
} else {
setState(() {
_geocodingResult = 'No results found';
});
}
}
void _reverseGeocodeLocation() async {
double lat = 37.4219999;
double lng = -122.0840575;
LatLng location = LatLng(lat, lng);
GeocodingResponse response = await _geocoding.reverseGeocodeLocation(location);
if (response.results.isNotEmpty) {
setState(() {
_reverseGeocodingResult = response.results.first.formattedAddress;
});
} else {
setState(() {
_reverseGeocodingResult = 'No results found';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Maps Web Services Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Geocoding Result: $_geocodingResult'),
SizedBox(height: 20),
ElevatedButton(
onPressed: _geocodeAddress,
child: Text('Geocode Address'),
),
SizedBox(height: 40),
Text('Reverse Geocoding Result: $_reverseGeocodingResult'),
SizedBox(height: 20),
ElevatedButton(
onPressed: _reverseGeocodeLocation,
child: Text('Reverse Geocode Location'),
),
],
),
),
);
}
}
说明:
- API 密钥:你需要一个有效的谷歌地图 API 密钥。在代码中替换
'YOUR_API_KEY'
为你的实际 API 密钥。 - 地理编码:点击“Geocode Address”按钮,会将一个地址转换为地理坐标(经纬度)。
- 反向地理编码:点击“Reverse Geocode Location”按钮,会将地理坐标(经纬度)转换为地址。
确保你的 API 密钥具有适当的权限来访问地理编码和反向地理编码服务。你可以在谷歌云控制台中配置这些权限。
这个示例代码展示了如何使用 googlemaps_flutter_webservices
插件的基本功能。根据需求,你可以进一步扩展和自定义这些功能。