lookupAddress method
查询地址获取地理位置信息
address
要查询的地址
返回地理位置信息,如果未找到则返回null
Implementation
Future<GeoLocation?> lookupAddress(String address) async {
if (address.isEmpty) {
print('地址查询失败: 地址为空');
return null;
}
try {
// 优先尝试使用在线API查询
// 打印完整URI,方便调试
final encodedAddress = Uri.encodeComponent(address);
final fullUrl = '$_nominatimApiUrl?q=$encodedAddress&format=json';
print('完整URI: $fullUrl');
// 构建请求参数
final queryParameters = {'q': address, 'format': 'json'};
print('搜索地址: $address');
// 发送GET请求,并设置更长的超时时间
final response = await _dio.get(
_nominatimApiUrl,
queryParameters: queryParameters,
options: Options(
// 为这个特定请求设置更长的超时时间
sendTimeout: const Duration(seconds: 60),
receiveTimeout: const Duration(seconds: 60),
),
);
print('API响应状态码: ${response.statusCode}');
if (response.statusCode == 200) {
final responseData = response.data;
// Dio已经自动将JSON转换为List
final List<dynamic> data = responseData;
print('API返回数据条数: ${data.length}');
if (data.isNotEmpty) {
final result = data.first;
print('选取的结果: $result');
// 确保lat和lon字段存在
if (result['lat'] == null || result['lon'] == null) {
print('API返回的数据缺少经度或纬度信息');
return null;
}
final double lat = double.parse(result['lat']);
final double lon = double.parse(result['lon']);
print('解析后的经纬度: 纬度=$lat, 经度=$lon');
final location = GeoLocation(
name: result['name'] ?? address,
displayName: result['display_name'] ?? address,
latitude: lat,
longitude: lon,
);
print('创建的地理位置对象: $location');
return location;
} else {
print('API返回的数据为空,尝试从本地数据中查找');
return await _searchLocalCityData(address);
}
} else {
print('API请求失败,状态码: ${response.statusCode},尝试从本地数据中查找');
return await _searchLocalCityData(address);
}
} on DioException catch (e) {
print('地址查询失败,Dio异常: ${e.message}');
if (e.type == DioExceptionType.connectionTimeout) {
print('连接超时,请检查网络连接或使用VPN');
} else if (e.type == DioExceptionType.receiveTimeout) {
print('接收数据超时,服务器响应过慢');
} else if (e.type == DioExceptionType.sendTimeout) {
print('发送数据超时,请检查网络连接');
}
print('详细错误: ${e.error}');
if (e.response != null) {
print('错误响应: ${e.response!.data}');
}
// 从本地数据中查找
print('尝试从本地数据中查找地址信息');
final localResult = await _searchLocalCityData(address);
if (localResult != null) {
return localResult;
}
// 如果实在找不到,可以给出一个友好提示
print('在本地数据中未找到匹配的地址: $address');
return null;
} catch (e) {
print('地址查询失败,发生异常: $e');
// 尝试从本地数据中查找
return await _searchLocalCityData(address);
}
}