BSavaliya BSavaliya - 4 months ago 51
TypeScript Question

How to add marker click listener in IONIC2?

I am working with IONIC2, i have implement map and put markers on the map.
I can get map click listener but can not get Marker click listener.

I had tried addlistener also but can not get click event for marker.

Here is my code for adding marker on map:

addMarkerOnMap(latLng1: GoogleMapsLatLng, depotsEntity: DepotsEntity) {
/**
* To add marker in the map, need to initialize GoogleMapsMarkerOptions
*/
let options: GoogleMapsMarkerOptions = {
icon: "www/img/location.png",
title: depotsEntity.address,
position: latLng1,
animation: GoogleMapsAnimation.DROP
};
let marker = this.map.addMarker(options)
this.map.on(this.map.markerClicked, function () {
console.log("markerClicked"); // This is not working yet

});


Please help me if anybody knows regarding marker click listener in IONIC2.

Answer

Looking at your code I will assume that you are using cordova-plugin-googlemaps.

There are a couple of things you are doing wrong. The first is that map.addMarker() doesn't return a marker, instead it returns a promise with a value of type GoogleMapsMarker which makes this line incorrect

let marker = this.map.addMarker(options)

Secondly, you attach the event handler to the marker object and not to the map which means this bit is also wrong

this.map.on(this.map.markerClicked, function () { });

What you need to do is call this.map.addMarker(), wait until the promise is resolved, and add the click handler to the marker returned by the promise.

Example

this.map.addMarker(options).then((marker: GoogleMapsMarker) => {
        marker.addEventListener(GoogleMapsEvent.MARKER_CLICK).subscribe(() => { console.log('Marker clicked...'); });
});

You will need to make sure GoogleMapsMarker and GoogleMapsEvent have been imported from ionic-native.

Note

As of writing this I have theoretically showed you how to implement what you want but at the minute this is likely to give you the following error

this._next is not a function

This is a known issue and as far as I can tell it happens on any map / marker event that you have to subscribe to. The issue can be tracked on the Ionic Native GitHub page #206.

Comments