In this code sample, I want to show the distance attribute on top of the PolyLine with an offset of 45% (almost next to the arrow). But I was not successful in achieving that.
<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>
creating a sibling component as an overlay throws DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
Edit: I have implemented a solution with
<OverlayView
position={getMiddlePosition(source, destination)}
mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
getPixelPositionOffset={(width, height) => ({ x: -10, y: -10 })}
>
<div> the text here </div>
</OverlayView>
But it is not always in the desired position like the arrow, especially in zoom in/zoom out it does not look nice. Is there any way to create a custom icon with modifiable text that can be added to the list of Polyline icons?
[EDIT] You can use the Geometry Library to get the % offset between two points
Inside your
onloadfunction from the<Map />component, you can use the Geometry Library of Maps Javascript API to calculate the following with its respective methods:computeDistanceBetween()- to get the distance between pointscomputeHeading()- to compute the heading to be used incomputeOffsetMethod.computeOffset()- to get the latLng of the offset distance from the origin.Combining the three and a little math, will give you the desired results.
First is to include the
"geometry"library:Then create a state for the calculated results to be used as a position for your
<InfoWindow />component.Then inside your
onloadfunction from the component, you will use the Geometry Library to do the following:Lastly, your
<InfoWindow />component should look like this and should be a direct child of the<GoogleMaps />component:Your whole return should look like this:
Here's what your map should look like with
45%offset:I hope this helps! Here's a proof of concept snippet for you to check and play around with: 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