reactjs - 如何将文本附加到 React Google Maps Api Polyline

标签 reactjs google-maps google-maps-api-3 google-polyline react-google-maps-api

In this code sample ,我想在折线顶部显示距离属性,偏移量为 45%(几乎在箭头旁边)。但我并没有成功实现这一目标。

  <GoogleMap
      id="react-google-maps"
      mapContainerClassName={"google-map-container-style"}
      onLoad={onLoad}
      onUnmount={onUnmount}
      onZoomChanged={() => {}}
    >
      {data.map(({ source, destination, distance }, index) => (
        <Polyline
          key={index}
          options={{
            strokeColor: "#4468E1",
            icons: [
              {
                icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW },
                offset: "50%"
              }
            ]
          }}
          path={[source, destination]}
        />
        /* If I wrap this section in a Fragment or div and render another overlay component here as a sibling, will receive the below error*/
      ))}
    </GoogleMap>

创建同级组件作为叠加层会抛出DOMException:无法在“Node”上执行“insertBefore”:要在其之前插入新节点的节点不是此节点的子节点。

编辑:我已经实现了一个解决方案

            <OverlayView
              position={getMiddlePosition(source, destination)}
              mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
              getPixelPositionOffset={(width, height) => ({ x: -10, y: -10 })}
            >
              <div> the text here </div>
            </OverlayView>

但它并不总是像箭头一样位于所需的位置,尤其是在放大/缩小时它看起来不太好。有没有办法创建带有可修改文本的自定义图标,并将其添加到折线图标列表中?

最佳答案

[编辑]您可以使用几何库来获取两点之间的偏移百分比

在你的 onload 里面函数来自 <Map />组件,您可以使用Geometry Library Maps Javascript API 使用其各自的方法计算以下内容:

  1. computeDistanceBetween() - 获取点之间的距离
  2. computeHeading() - 计算 computeOffsetMethod 中使用的标题.
  3. computeOffset() - 获取距原点的偏移距离的 latLng。

将三者结合起来并进行一些数学计算,将为您提供所需的结果。

首先是包含 "geometry"图书馆:

const libraries: Libraries = ["drawing", "geometry"];

然后为计算结果创建一个状态,用作您的 <InfoWindow /> 的位置组件。

const [polylineText, setPolylineText] = useState<
  google.maps.LatLng | google.maps.LatLngLiteral | undefined
>(undefined);

然后在你的 onload 里面从组件中调用函数,您将使用几何库执行以下操作:

// store the spherical property in a variable for later use
const compute = google.maps.geometry.spherical;

// use computeDistanceBetween() method
// to get the distance between the two locations for calculating the offset Length
const distanceBetween = compute.computeDistanceBetween(
  location1,
  location2
);
console.log("Distance Between: " + distanceBetween);

// multiply the distance to 0.45 to get the 45% of its length
// You can change the value here if you want to modify it
// ex. multiplying it with 0.5 will provide you the center.
const offsetDistance = distanceBetween * 0.45;
console.log("Offset length: " + offsetDistance);

// use computeHeading() method to get the heading for later use
const heading = compute.computeHeading(location1, location2);
console.log("Heading: " + heading);

// use the computeOffset() method to get the latLng of the offsetDistance
const offsetLocation = compute.computeOffset(
  location1,
  offsetDistance,
  heading
);
console.log("Offset location: " + offsetLocation);

// update the state for the position of your infoWindow
setPolylineText(offsetLocation);

最后,您的<InfoWindow />组件应该如下所示,并且应该是 <GoogleMaps /> 的直接子级组件:

<InfoWindow position={polylineText}>
  <div>
    <p>Distance Between Points: {data[1].distance}</p>
  </div>
</InfoWindow>

NOTE: As this is just a demonstration on how to do the calculations, its up to you to do the map() method if you're dealing with lots of points/polylines/data

您的整个返回应如下所示:

return !isLoaded ? null : (
  <GoogleMap
    id="react-google-maps"
    mapContainerClassName={"google-map-container-style"}
    onLoad={onLoad}
    onUnmount={onUnmount}
    onZoomChanged={() => {}}
  >
<InfoWindow position={polylineText}>
<div>
  <p>Distance Between Points: {data[1].distance}</p>
</div>
</InfoWindow>
    {data.map(({ source, destination, distance }, index) => (
      <Marker key={index} position={source}></Marker>
    ))}
    {data.map(({ source, destination, distance }, index) => (
      <Polyline
        key={index}
        options={{
          strokeColor: "#4468E1",
          icons: [
            {
              icon: { path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW },
              offset: "50%"
            }
          ]
        }}
        path={[source, destination]}
      />
    ))}
  </GoogleMap>
);

您的 map 应如下所示 45%偏移量:

Final result

我希望这有帮助!这是一个概念证明片段供您检查和使用:https://codesandbox.io/s/how-to-attach-a-text-to-react-google-maps-api-polyline-using-geometry-library-r8ij7h?file=/src/App.tsx:3108-3949

关于reactjs - 如何将文本附加到 React Google Maps Api Polyline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76342282/

相关文章:

google-maps - 向谷歌地图添加许多圆圈

reactjs - Redux 传奇 : What is the difference between using yield call() and async/await?

reactjs - React Router 未指定输入文件

ios - GoogleMaps 不是 dylib,最新版本的 pod 文件编译时错误

javascript - 将 php json 传递给 google map API 的 javascript 对象

javascript - Google Maps API v3 - 标记全部共享相同的信息窗口

javascript - onClick 从类更改为函数

javascript - 使用 Rails asset pipeline 与 webpack 来保存 Assets 的优缺点是什么?

java - 如何获取给定城市名称或地址的纬度和经度(java代码)?

google-maps - 如何在 Google Places API 上唯一标识一个地点