IONIC 2 Google Maps Marker Click Event

2019-03-31 08:06发布

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);
               });
          });       
}

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-31 08:46

Subscribe event is asynchronous.You will not get record.id from the for loop. But you can access markerOptions data in subscribe.

Check here

    this.map.addMarker(markerOptions).then((marker: GoogleMapsMarker) => {
             marker.addEventListener(GoogleMapsEvent.MARKER_CLICK)
            .subscribe(e => {
              alert(e.get('title'));
let rec = data1.filter(v=>v.title==e.get('title'));
alert(rec[0].id);
                   });
              });

And here

查看更多
趁早两清
3楼-- · 2019-03-31 08:46

for those who still have this problem

this.map
  .addMarker({
    title: title,
    index: index,
    icon: {
      size: {
        height: 48,
        width: 30

      },
      url: pinUri
    },
    position: {
      lat: latitude,
      lng: longuitud
    }
  })
  .then(marker => {

    marker
      .on(GoogleMapsEvent.MARKER_CLICK)
      .subscribe((selectedMarker: any) => {
        const mark = selectedMarker[1];
        this.showModal(mark.get('index'), true);
      });

  });
查看更多
登录 后发表回答