You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Mapbox无法显示起点到点击地点的路线求助

React Native Mapbox 路线不显示问题修复方案

1. 坐标顺序错误(核心问题)

Mapbox要求坐标格式为**[经度, 纬度],但polyline.decode返回的是[纬度, 经度]**。你代码中虽转换了routeGeometry,但实际赋值给coordinates的是未转换的routeCoordinates,导致路线坐标顺序颠倒,地图无法正确渲染。

修复代码:

const routeFeature = {
  type: 'Feature',
  properties: {},
  geometry: {
    type: 'LineString',
    coordinates: routeGeometry, // 改用转换后的routeGeometry
  },
};

2. useState异步更新导致的坐标错误

setSelectedLocation是异步操作,在handleMapPress中调用后立刻执行fetchAndDisplayRoute,此时selectedLocation仍为旧值,会导致请求的路线起点/终点错误。直接使用事件返回的坐标即可:

修复代码:

const handleMapPress = (event) => {
  const newLocation = event.geometry.coordinates;
  setSelectedLocation(newLocation);
  fetchAndDisplayRoute(newLocation); // 直接传递新坐标
};

// 修改fetchAndDisplayRoute参数
const fetchAndDisplayRoute = async (targetLocation) => {
  try {
    const response = await fetch(
      `https://api.mapbox.com/directions/v5/mapbox/driving/${initialLng},${initialLat};${targetLocation[0]},${targetLocation[1]}?access_token=<TOKEN>`
    );
    // 剩余代码不变...
  } catch (error) {
    console.error('Error fetching and displaying route:', error);
  }
};

3. 路线样式不可见

检查styles.route是否设置了足够明显的样式,否则即使路线存在也可能看不到:

示例样式:

const styles = StyleSheet.create({
  // 其他样式...
  route: {
    lineColor: '#2196F3', // 蓝色路线
    lineWidth: 4, // 足够宽的线宽
  },
});

4. 初始状态处理

routeFeatureCollection初始为null,ShapeSource在shape为null时不会渲染。可以给一个空的FeatureCollection作为初始值,避免渲染异常:

const [routeFeatureCollection, setRouteFeatureCollection] = useState({
  type: 'FeatureCollection',
  features: []
});

完整修复后的关键代码片段

const fetchAndDisplayRoute = async (targetLocation) => {
  try {
    const response = await fetch(
      `https://api.mapbox.com/directions/v5/mapbox/driving/${initialLng},${initialLat};${targetLocation[0]},${targetLocation[1]}?access_token=<TOKEN>`
    );
    const routeData = await response.json();
    console.log('Route Data:', routeData);
    const routeCoordinates = polyline.decode(routeData.routes[0].geometry);

    // 转换为Mapbox要求的[经度, 纬度]格式
    const routeGeometry = routeCoordinates.map(coord => [coord[1], coord[0]]);
    
    const routeFeature = {
      type: 'Feature',
      properties: {},
      geometry: {
        type: 'LineString',
        coordinates: routeGeometry,
      },
    };

   const newRouteFeatureCollection = {
      type: 'FeatureCollection',
      features: [routeFeature], 
    };

    setRouteFeatureCollection(newRouteFeatureCollection);
  } catch (error) {
    console.error('Error fetching and displaying route:', error);
  }
};

const handleMapPress = (event) => {
  const newLocation = event.geometry.coordinates;
  setSelectedLocation(newLocation);
  fetchAndDisplayRoute(newLocation);
};

内容的提问来源于stack exchange,提问作者Crdnpyaad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:35:52