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

React Native Google Maps绘制多条Polyline问题求助

解决React Native Google地图绘制多条折线的问题

嘿,这个问题我之前也碰到过!核心原因是你现在应该是用单个变量存储折线坐标,每次请求新路线时直接覆盖了旧数据,所以地图上只会显示最后一条折线。咱们可以通过维护一个折线数组来解决这个问题,具体步骤如下:

1. 调整状态管理

把原来存储单组折线坐标的状态,改成存储多组折线的数组:

import React, { useState, useEffect } from 'react';
import { View } from 'react-native';
import MapView, { Polyline } from 'react-native-maps';
import polyline from '@mapbox/polyline';

const MapScreen = () => {
  // 用数组存储所有折线的坐标集合
  const [polylines, setPolylines] = useState([]);
  // 地图初始区域示例
  const initialRegion = {
    latitude: 37.78825,
    longitude: -122.4324,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  };

2. 批量添加折线数据

每次获取到一组起点-终点的路线后,先解码坐标,再把这条路线追加到折线数组里(注意不要直接替换数组,要用展开运算符保留之前的数据):

// 示例:获取并添加一条折线的函数
const addPolyline = async (startCoords, endCoords) => {
  // 替换成你的路线API请求(比如Google Directions API)
  const response = await fetch(`YOUR_API_ENDPOINT?origin=${startCoords.lat},${startCoords.lng}&destination=${endCoords.lat},${endCoords.lng}`);
  const data = await response.json();
  // 解码路线坐标
  const routeCoords = polyline.decode(data.routes[0].overview_polyline.points);
  // 转换成MapView需要的格式
  const formattedCoords = routeCoords.map(([lat, lng]) => ({ latitude: lat, longitude: lng }));
  // 将新折线添加到数组中
  setPolylines(prev => [...prev, formattedCoords]);
};

// 组件挂载时添加多条折线示例
useEffect(() => {
  // 第一条折线:起点A → 终点B
  addPolyline({ lat: 37.78825, lng: -122.4324 }, { lat: 37.7749, lng: -122.4194 });
  // 第二条折线:起点C → 终点D
  addPolyline({ lat: 37.7600, lng: -122.4400 }, { lat: 37.7900, lng: -122.4000 });
}, []);

3. 循环渲染所有折线

在MapView内部,通过map方法遍历折线数组,渲染每个Polyline组件,记得给每个组件加唯一的key值:

return (
    <View style={{ flex: 1 }}>
      <MapView initialRegion={initialRegion} style={{ flex: 1 }}>
        {polylines.map((coords, index) => (
          <Polyline
            key={`polyline-${index}`}
            coordinates={coords}
            strokeColor={index % 2 === 0 ? '#FF0000' : '#0000FF'} // 用不同颜色区分折线
            strokeWidth={3}
          />
        ))}
      </MapView>
    </View>
  );
};

export default MapScreen;

效果示例

你提到的多折线效果大概是这样的:
React Native Google地图上的多条折线示例

这样修改后,每次添加新的折线都会被保留在数组里,地图上就会显示所有的折线啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:04:31