MapViewDirections请求GMAPS路线返回ZERO_RESULTS 终点坐标异常问题
问题修复方案
1. 服务端返回终点坐标为-1,-1的问题
你的代码存在多处语法错误和变量引用错误,直接导致坐标读取失败:
- 状态声明语法错误:
const [ endRun setEndRun ] = useState(null)缺少逗号,应为const [endRun, setEndRun] = useState(null) - 变量引用错误:
finalLocation方法中请求返回的变量名为running_response,赋值时错误引用了不存在的client_response - 属性读取语法错误:读取end_lon时缺少左侧引号,应为
["end_lon"],你写的是[end_lon"] - 未做返回值校验:服务端返回-1说明你需要先排查用户提交终点的上传接口,是否正确将用户选择的终点坐标存储到了服务端,确认存储逻辑正常后再做前端取值校验,过滤无效的-1坐标
2. 硬编码坐标仍无法渲染路线的问题
React的状态更新是异步操作,你在调用完取值方法后直接渲染路线组件,此时状态还未完成更新,组件拿到的是初始的null或0值,触发谷歌接口报错:
- 需在
startRun和endRun两个状态都被赋值为有效坐标后,再渲染MapViewDirections组件 - 确认你已经给
MapViewDirections组件传入了有效的谷歌地图API密钥,且该密钥开通了路线服务权限
修正后的代码示例
const [user_latitude, setUserLatitude] = useState(0) const [user_longitude, setUserLongitude] = useState(0) const [startRun, setStartRun] = useState(null) const [endRun, setEndRun] = useState(null) useFocusEffect( React.useCallback(() => { let isActive = true; const fetchGeoPosition = () => { //获取跑步者当前位置 navigator.geolocation.getCurrentPosition( position => { if(isActive){ const lat = position.coords.latitude const lon = position.coords.longitude setUserLatitude(lat) setUserLongitude(lon) // 定位成功后再设置起点,避免取初始0值 setStartRun({ latitude: lat, longitude: lon }) } } ) } const finalLocation = async() => { try { const running_response = await client_instance.get_final_locations() const endLat = running_response["location_info"]["end_lat"] const endLon = running_response["location_info"]["end_lon"] // 校验坐标有效性,过滤-1的无效值 if(endLat !== -1 && endLon !== -1) { setEndRun({ latitude: endLat, longitude: endLon }) } } catch (err) { console.error("拉取终点坐标失败:", err) } } fetchGeoPosition() finalLocation() return () => { isActive = false } }, []) ) // 渲染时增加非空判断,仅坐标有效时渲染对应组件 return ( <> {startRun && <Marker coordinate={startRun}/>} {endRun && <Marker coordinate={endRun}/>} {startRun && endRun && ( <MapViewDirections origin={startRun} destination={endRun} strokeWidth={5} apikey="你的谷歌地图API密钥" /> )} </> )
内容的提问来源于stack exchange,提问作者MK_Pierce
相关产品推荐
相关产品推荐

