I have created a Google Map in my web page and it is already loaded. On a button click, I'm getting some data and creating a Polyline, e.g.
this.poly = new google.maps.Polyline({
strokeColor: '#00FF00',
strokeOpacity: 0.5,
strokeWeight: 2,
map:this.config.gmap,
path:input.data.map(function(x) {
return new google.maps.LatLng(x.lat,x.lon)
})
})
Then I'm trying to add an event listener so I can process clicks on the polyline. At the moment I'm just printing a debug statement to the console so I know the event fired:
this.poly.addListener("click",(e)=>{
console.log("DEBUG:",e)
})
However, clicking (or more accurately tapping on the screen) doesn't fire the event. Instead, on the console I see this error thrown inside the Google Maps library:
[Intervention] Ignored attempt to cancel a touchmove event with cancelable=false, for example because scrolling is in progress and cannot be interrupted.
Update: I think this message may be a red herring because it occurs anywhere I click on the map, even if I didn't add an event listener.
I also tried using google.maps.event.addListener(this.poly,"click",
... (which is implied as a given to "just work" in this question, this question, and this question ) with the same result - no event ever fires!
However, if I add the listener directly from the Chrome developer console, then tapping on the polyline produces the expected console output. From this I am guessing that maybe I need to wait for the polyline to actually be loaded before I can add events to it. I was going to try to wait for the DOM element to be loaded, but the object returned isn't part of the DOM and it isn't documented how to get the DOM element. I haven't found anything in the documentation that tells me how to listen for any events to tell me when a newly created element has been added to the map, so perhaps my guess is wrong.
How do I correctly set up the polyline click event to fire?
Update: As a workaround I can also get the event to work if I simply wrap the addListener call in a setTimeout:
this.poly = new google.maps.Polyline({
strokeColor: '#00FF00',
strokeOpacity: 0.5,
strokeWeight: 2,
map:this.config.gmap,
path:input.data.map(function(x) {
return new google.maps.LatLng(x.lat,x.lon)
})
})
setTimeout(()=> {
this.poly.addListener("click",(e)=>{
console("DEBUG2:",e)
})
},1000)
This seems to support the notion that it isn't safe to add an event immediately after creating a new element. I'm creating the new element inside of an async function itself called by another event handler so I don't know if perhaps the Maps API doesn't like that for some reason. But this workaround isn't particularly satisfying because I would like the click to be available as soon as possible, and there isn't any documentation on how low I can set the timeout and have it always work.