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

如何在react-native-maps-directions中实现多条备选路线显示?

实现react-native-maps的多条备选驾车路线

react-native-maps-directions库本身不支持返回备选路线,它默认仅请求并渲染Google Directions API返回的第一条路线。要实现类似谷歌地图的多路线功能,需要直接调用Google Maps Directions API并开启备选路线参数,再手动渲染每条路线。


核心思路

  1. 调用Google Directions API时添加alternatives=true参数,获取所有备选路线数据
  2. 解码API返回的编码折线数据,转换为地图可识别的坐标数组
  3. 使用MapView.Polyline组件渲染每条路线,区分主路线与备选路线的样式
  4. 添加点击交互,切换选中路线并更新距离/时长信息

修改后的完整代码示例

import React, { useState, useEffect } from 'react';
import MapView, { Marker, PROVIDER_GOOGLE, Polyline } from "react-native-maps";
import { GooglePlacesAutocomplete } from "react-native-google-places-autocomplete";
import polyline from '@mapbox/polyline'; // 需要先安装:npm install @mapbox/polyline

const YourMapComponent = () => {
  const [origin, setOrigin] = useState(null);
  const [destination, setDestination] = useState(null);
  const [routes, setRoutes] = useState([]);
  const [selectedRouteIndex, setSelectedRouteIndex] = useState(0);
  const googleAPIKey = '你的Google API密钥';
  const middleOfDenmark = { /* 你的初始区域配置 */ };

  // 解码Google返回的编码折线为坐标数组
  const decodePolyline = (encoded) => {
    return polyline.decode(encoded).map(([lat, lng]) => ({
      latitude: lat,
      longitude: lng
    }));
  };

  // 调用Google Directions API获取多路线数据
  const fetchDirections = async () => {
    if (!origin || !destination) return;
    const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&mode=driving&alternatives=true&key=${googleAPIKey}`;
    
    try {
      const response = await fetch(url);
      const data = await response.json();
      if (data.status === 'OK') {
        setRoutes(data.routes);
        // 初始化显示第一条路线的距离
        calcDistanceOnReady({
          distance: data.routes[0].legs[0].distance,
          duration: data.routes[0].legs[0].duration
        });
      }
    } catch (error) {
      console.error('获取路线失败:', error);
    }
  };

  // 起点/终点变化时重新获取路线
  useEffect(() => {
    if (origin && destination) {
      fetchDirections();
    }
  }, [origin, destination]);

  // 原有的距离计算函数
  const calcDistanceOnReady = (result) => {
    // 这里处理距离/时长的展示逻辑
    console.log('当前路线距离:', result.distance.text);
    console.log('当前路线时长:', result.duration.text);
  };

  return (
    <>
      {/* 你的GooglePlacesAutocomplete组件 */}
      <MapView
        ref={mapRef}
        style={styles.map}
        provider={PROVIDER_GOOGLE}
        initialRegion={middleOfDenmark}
      >
        {origin && <Marker coordinate={origin} />}
        {destination && <Marker coordinate={destination} />}
        {/* 渲染所有备选路线 */}
        {routes.map((route, index) => (
          <Polyline
            key={index}
            coordinates={decodePolyline(route.overview_polyline.points)}
            strokeColor={index === selectedRouteIndex ? '#112D4E' : '#888888'}
            strokeWidth={index === selectedRouteIndex ? 4 : 3}
            onPress={() => {
              setSelectedRouteIndex(index);
              // 切换路线时更新距离显示
              calcDistanceOnReady({
                distance: route.legs[0].distance,
                duration: route.legs[0].duration
              });
            }}
          />
        ))}
      </MapView>
    </>
  );
};

const styles = {
  map: {
    flex: 1
  }
};

export default YourMapComponent;

注意事项

  • 确保你的Google API密钥已启用Directions API
  • 多路线请求会消耗更多API配额,注意监控使用量
  • 可自定义样式:比如给选中路线添加虚线效果、阴影,提升视觉区分度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:00:31