Reputation: 43
thanks again for the great here map API.
We are currently struggling how to determine if a marker or the map itself was clicked. We have added event listeners to both the map and the marker (added as group).
When we now click on the map, both eventlisteners are fired.
Do we miss something in the API docs? I think there should be a way to get correct information of what was clicked.
Map event listener
map.addEventListener('tap', (event) => {
action(event);
});
Marker event listener
marker.addEventListener('tap', (event) => {
action(event);
});
Thanks in advance.
Upvotes: 2
Views: 1769
Reputation: 28359
Better stay with a single listener on the map object.
The key thing is to check the instance of the event.target
:
map.addEventListener('tap', event => {
if (event.target instanceof H.map.Marker) {
// Some action. Typically, you want to use the data that you may have referenced
// in the marker creation code, or get the coordinates. Here we log the data
console.log( event.target.getData() );
}
}
Upvotes: 2
Reputation: 145
Hey this small example works fine for me, I see in the docs there is not listener for tap, these are the supported listeners.
https://developers.google.com/maps/documentation/javascript/events
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Markers</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map, marker;
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
map.addListener('click', (event) => {
console.log(event, 'from map')
});
marker.addListener('click', (event) => {
console.log(event, 'from marker')
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
</body>
</html>
Upvotes: 0