如何从Google Maps DistanceMatrix API响应中提取距离?
从Google Maps DistanceMatrix API响应中提取距离的方法
首先注意:Dio的get方法返回的response对象包含多个属性,实际的API响应数据在response.data中,你需要先获取这个属性再进行解析。
修改后的代码示例
getDistanceMatrix() async { try { var response = await Dio().get('https://maps.googleapis.com/maps/api/distancematrix/json?destinations=${widget.miLatitud},${widget.miLongitud}&origins=${location.latitude},${location.longitude}&key=...'); // 提取响应数据 var responseData = response.data; // 检查API请求状态是否正常 if (responseData['status'] == 'OK') { // 提取距离信息 String distanceText = responseData['rows'][0]['elements'][0]['distance']['text']; int distanceValue = responseData['rows'][0]['elements'][0]['distance']['value']; print("距离文本:$distanceText"); print("距离数值(米):$distanceValue"); } else { print("API请求失败:${responseData['status']}"); } } catch (e) { print("请求出错:$e"); } }
代码说明
response.data:Dio请求返回的JSON格式响应体,直接通过键值对访问即可responseData['rows'][0]:因为你只请求了一组起点和终点,所以取第一个rowelements[0]:单组起点终点对应第一个elementdistance['text']:带单位的可读距离(比如13.0 km)distance['value']:以米为单位的数值距离(比如13012,即13012米)
额外提示
如果需要处理多组起点/终点的情况,需要遍历rows和elements数组,根据实际需求提取对应位置的距离数据。
内容的提问来源于stack exchange,提问作者mvasco
相关产品推荐
相关产品推荐

