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

使用react-google-maps时,如何修改路径段strokeColor及设置DirectionsService回调

嘿,刚好我之前在react-google-maps里处理过类似的需求,给你拆解一下这两个问题的解决办法!

一、DirectionsService调用后的回调函数设置

其实DirectionsService.route()方法本身就支持传入回调函数作为第二个参数,当路线请求完成(成功或失败)时就会触发这个回调。在React项目里,你可以把这个回调和组件的状态更新、后续业务逻辑结合起来。

举个函数组件的例子:

import { useEffect } from 'react';
import { useLoadScript } from '@react-google-maps/api';

const MapComponent = () => {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: '你的API密钥',
    libraries: ['geometry'], // 解析路径编码需要用到这个库
  });

  useEffect(() => {
    if (!isLoaded) return;

    const directionsService = new google.maps.DirectionsService();
    const routeRequest = {
      origin: '北京',
      destination: '上海',
      waypoints: [{ location: '济南', stopover: true }, { location: '南京', stopover: true }],
      travelMode: google.maps.TravelMode.DRIVING,
    };

    // 这里就是调用后的回调函数
    directionsService.route(routeRequest, (result, status) => {
      if (status === google.maps.DirectionsStatus.OK) {
        // 成功获取路线后的逻辑:比如更新组件状态、渲染自定义路径等
        console.log('路线请求成功:', result);
        // 这里可以触发你的自定义逻辑,比如通知父组件、保存路线数据等
      } else {
        // 处理失败情况
        console.error('路线请求失败:', status);
      }
    });
  }, [isLoaded]);

  if (!isLoaded) return <div>地图加载中...</div>;
  // 后续地图渲染逻辑
  return <div>地图容器</div>;
};

这个回调就是你要的“调用后处理逻辑”的入口,不管请求成功还是失败,都能在这里做对应的操作。

二、修改途经点各路径段的strokeColor

默认的DirectionsRenderer组件没办法单独给不同途经点之间的路径段设置不同颜色,所以我们需要放弃使用DirectionsRenderer,手动解析路线结果并渲染多个Polyline组件,每个Polyline对应一段路径,单独设置颜色。

完整代码示例:

import { useState, useEffect } from 'react';
import { GoogleMap, Polyline, useLoadScript } from '@react-google-maps/api';
import { geometry } from 'google.maps';

const CustomRouteMap = () => {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: '你的API密钥',
    libraries: ['geometry'],
  });
  const [routePolylines, setRoutePolylines] = useState([]);

  useEffect(() => {
    if (!isLoaded) return;

    const directionsService = new google.maps.DirectionsService();
    const request = {
      origin: '北京',
      destination: '上海',
      waypoints: [
        { location: '济南', stopover: true },
        { location: '南京', stopover: true }
      ],
      travelMode: google.maps.TravelMode.DRIVING,
    };

    directionsService.route(request, (result, status) => {
      if (status !== google.maps.DirectionsStatus.OK) {
        console.error('获取路线失败:', status);
        return;
      }

      // 定义各路段的颜色,按顺序对应origin->waypoint1, waypoint1->waypoint2, waypoint2->destination
      const segmentColors = ['#FF4444', '#44FF44', '#4444FF'];
      const routes = result.routes[0];

      // 遍历每个leg,生成对应的Polyline配置
      const polylines = routes.legs.map((leg, index) => {
        // 把当前leg下所有step的路径合并成一个坐标数组
        const path = leg.steps.flatMap(step => 
          geometry.encoding.decodePath(step.polyline.points)
        );
        return {
          path,
          strokeColor: segmentColors[index % segmentColors.length],
          strokeOpacity: 0.9,
          strokeWeight: 6,
        };
      });

      setRoutePolylines(polylines);
    });
  }, [isLoaded]);

  if (!isLoaded) return <div>地图加载中...</div>;

  return (
    <GoogleMap
      mapContainerStyle={{ width: '100%', height: '600px' }}
      center={{ lat: 39.9042, lng: 116.4074 }}
      zoom={6}
    >
      {/* 渲染所有自定义颜色的路径段 */}
      {routePolylines.map((polyline, idx) => (
        <Polyline key={idx} {...polyline} />
      ))}
    </GoogleMap>
  );
};

export default CustomRouteMap;

简单解释下:

  • legs数组的长度等于途经点数量+1(比如2个途经点就有3个leg,对应3段路径)
  • 用geometry.encoding.decodePath()把谷歌返回的路径编码转换成坐标数组,供Polyline使用
  • 给每个leg对应的Polyline分配不同的strokeColor,实现分段染色的效果

这样就能完美解决你的两个问题啦!

内容的提问来源于stack exchange,提问作者Thuc Hồ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:40:11