问题描述
我尝试使用“ geolocation and geocode”的dart插件来获取位置。但是代码给出了“未处理的异常:PlatformException(Failed,Failed,null)”错误。我该如何克服?
import 'package:geolocator/geolocator.dart';
import 'package:geocoder/geocoder.dart';
Future<String> getCurrentLocation() async {
final location = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
String latitude =(location.latitude).toString();
String longitude = (location.longitude).toString();
String _center = latitude + "," + longitude;
print(_center);
final coordinates = await new Coordinates(location.latitude,location.longitude);
var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print("${first.featureName} : ${first.addressLine}");
return _center;
}
解决方法
添加您的apikey,它将起作用:
var addresses = await Geocoder.google ( '<---------YOUR APIKEY-------->' ).findAddressesFromCoordinates(coordinates);
,
您需要在 Google Cloud Platform 中创建一个密钥并为其启用 Geocoder API
使用:
await Geocoder.google(your_API_Key).findAddressesFromCoordinates(coordinates);
代替:
await Geocoder.local.findAddressesFromCoordinates(coordinates);