-3

If I add a Polyline to my map with a click function:

    onPolylineClick = (props, polyline) => {
        console.log(props)
        console.log(polyline)
    }

    <Polyline
        onClick={this.onPolylineClick}
        path={gpsCoords}
    />

Then how do I figure out where on the line it was clicked? I can see props.mapCenter but that doesn't change depending on where I click, it's just the centre of the map.

Pagemag
  • 2,779
  • 1
  • 7
  • 17
parsley72
  • 8,449
  • 8
  • 65
  • 98
  • 3
    Does this answer your question? [How to add marker onClick and show my geolocation in google-maps-react?](https://stackoverflow.com/questions/51421714/how-to-add-marker-onclick-and-show-my-geolocation-in-google-maps-react) – Nick is tired Aug 11 '20 at 07:34
  • @Nick no, I read that before I asked the question. That answer is for an onClick event from the map which doesn't tell me if the line was clicked. I want an onClick event from the line itself. – parsley72 Aug 12 '20 at 22:50

1 Answers1

1

You need to also pass a third parameter in your onPolylineClick since the latLng for the point you clicked in the polyline is there. You can do something like:

onPolylineClick = (props, polyline, e) => {
   console.log("Polyline Clicked on latlng: ")
   console.log(e.latLng.lat()+","+e.latLng.lng());
  };

You can check this sample code. Make sure to add your API Key in the GoogleApiWrapper for the code to properly run.

Pagemag
  • 2,779
  • 1
  • 7
  • 17
  • That works great, but how do I handle a Polyline with more than one segment? Can I tell which segment the user has clicked? – parsley72 Jul 28 '20 at 19:17
  • 1
    You can use a for loop to go through each segment and use [isLocationOnEdge()](https://developers.google.com/maps/documentation/javascript/geometry#isLocationOnEdge) of Google Maps JavaScript Geometry library to check which segment does the clicked point is nearer or lies to. Here's a [sample code](https://codesandbox.io/s/onpolylineclick-uhcwh). Take note however that this function has tolerance that might also result to showing the other nearest segment. If this would be your use case, I think you need to create multiple for each of your segments to be more accurate. – Pagemag Jul 29 '20 at 01:27