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

如何使用google-map-react在地图上绘制两点间Polyline折线?

实现方法

google-map-react 本身没有封装折线绘制的内置组件,需要拿到原生 Google Maps 实例后调用官方API完成两点连线,操作步骤如下:

  • 给GoogleMapReact组件绑定onGoogleApiLoaded回调,拿到原生map实例和maps核心对象
  • 在回调内定义两个坐标点的经纬度集合,调用maps.Polyline创建折线实例,配置路径、描边颜色、粗细等样式后绑定到地图实例
  • 组件卸载时手动清除创建的折线实例,避免内存泄漏

修改后的可运行核心代码如下,你可以直接替换原有逻辑:

import { useRef, useEffect } from 'react'
// 保留你原有的标记点组件引入
// import AnyReactComponent from '你的组件路径'

export default function MapPage() {
  // 保留你原有的中心点经纬度逻辑
  const lat = 39.9042
  const lng = 116.4074
  // 存储折线实例,用于后续清理
  const polylineRef = useRef(null)

  // 替换成你需要连线的两个实际坐标点
  const connectPoints = [
    { lat: 39.9042, lng: 116.4074 },
    { lat: 39.915, lng: 116.418 }
  ]

  const handleMapApiLoaded = (map, maps) => {
    // 创建折线实例
    const lineInstance = new maps.Polyline({
      path: connectPoints,
      geodesic: true, // 设为true则连线贴合地球曲面,平面地图可设为false
      strokeColor: "#2563eb", // 连线颜色,可自定义
      strokeOpacity: 1, // 连线透明度
      strokeWeight: 3, // 连线粗细,单位像素
    })
    // 将折线挂载到地图上显示
    lineInstance.setMap(map)
    polylineRef.current = lineInstance
  }

  // 组件卸载时清除折线,避免内存泄漏
  useEffect(() => {
    return () => {
      if (polylineRef.current) {
        polylineRef.current.setMap(null)
      }
    }
  }, [])

  return (
    <div className='videoDetails__map'>
      <GoogleMapReact
        bootstrapURLKeys={{
          key: "", // 填入你自己的谷歌地图API Key
        }}
        center={{
          lat: lat,
          lng: lng,
        }}
        defaultZoom={15}
        onGoogleApiLoaded={({ map, maps }) => handleMapApiLoaded(map, maps)}
        // 必须开启该属性才能拿到原生地图API实例
        yesIWantToUseGoogleMapApiInternals
      >
        <AnyReactComponent lat={lat} lng={lng} text='My Marker' />
        {/* 第二个标记点和第一个写法一致,传入对应经纬度即可 */}
      </GoogleMapReact>
    </div>
  )
}

注意:必须给GoogleMapReact组件添加yesIWantToUseGoogleMapApiInternals属性,否则无法触发API加载回调拿到原生实例。如果需要调整连线样式,直接修改Polyline配置项内的stroke相关参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 00:47:06