IONIC 2 Google Maps Marker Click Event

左心房为你撑大大i 提交于 2020-01-12 09:57:21

问题


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

回答1:


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




回答2:


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

  });


来源:https://stackoverflow.com/questions/41099774/ionic-2-google-maps-marker-click-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!