I'm trying to get all the markers from the database with this code. But the problem is when I click the marker I always get the last item from the database. When the "alert(record.id);" pops up it always show the last item for every marker. I want to show the id of each marker when I click them.
loadMarker(){
this.service.getMaps()
.subscribe( data1 => {
let loc = data1;
for (var i = 0; i < data1.length; i++) {
var record = data1[i];
let latlng = new GoogleMapsLatLng(record.lat, record.lng);
let markerOptions: GoogleMapsMarkerOptions = {
'position': latlng,
'title': record.title,
'animation': GoogleMapsAnimation.DROP
};
this.map.addMarker(markerOptions).then((marker: GoogleMapsMarker) => {
marker.addEventListener(GoogleMapsEvent.MARKER_CLICK)
.subscribe(() => {
alert(record.id);
});
});
}
Subscribe event is asynchronous.You will not get record.id from the for loop. But you can access markerOptions data in subscribe.
Check here
And here
for those who still have this problem