Angular-google-maps: Закрывать информационные окна маркера при нажатии нового?

Созданный на 19 дек. 2016  ·  23Комментарии  ·  Источник: SebastianM/angular-google-maps

Можно ли это сделать?

stale discussion / question

Самый полезный комментарий

Единственное решение для моего шаблона:

<sebm-google-map #gm [latitude]="lat" [longitude]="lng" [zoom]="zoom" [scrollwheel]="false" [styles]="mapStyles">
    <sebm-google-map-marker *ngFor="let place of places"
    [latitude]="place.point.lat"
    [longitude]="place.point.lng"
    [label]="place.name[0]"
    (markerClick)="gm.lastOpen?.close(); gm.lastOpen = infoWindow">
    <sebm-google-map-info-window #infoWindow>
        <strong>{{place.name}}</strong>
    </sebm-google-map-info-window>
</sebm-google-map-marker>

Все 23 Комментарий

Ага, я уже сталкивался с той же проблемой раньше.

Вот рабочая доска
http://plnkr.co/edit/cwuwBN?p=preview

я не мог использовать этот подход.
Мое решение было загружено из источников и включало в файл следующий код (google-map-info-window.ts):

// устанавливаем это свойство в верхнем файле, ниже let infoWindowId = 0; (строка 7)
пусть infoWindowLastContext: SebmGoogleMapInfoWindow = null;

open (): Обещание{
if (infoWindowLastContext! == null) {
this._infoWindowManager.close (infoWindowLastContext)
}

infoWindowLastContext = this;

return this._infoWindowManager.open(this);

}

Надеюсь, это поможет...

Единственное решение для моего шаблона:

<sebm-google-map #gm [latitude]="lat" [longitude]="lng" [zoom]="zoom" [scrollwheel]="false" [styles]="mapStyles">
    <sebm-google-map-marker *ngFor="let place of places"
    [latitude]="place.point.lat"
    [longitude]="place.point.lng"
    [label]="place.name[0]"
    (markerClick)="gm.lastOpen?.close(); gm.lastOpen = infoWindow">
    <sebm-google-map-info-window #infoWindow>
        <strong>{{place.name}}</strong>
    </sebm-google-map-info-window>
</sebm-google-map-marker>

@soyersoyer @lazarljubenovic

<agm-map #gm [latitude]="lat" [longitude]="lng" [zoom]="zoom" [scrollwheel]="false" [styles]="mapStyles">
    <sebm-google-map-marker *ngFor="let place of places"
    [latitude]="place.point.lat"
    [longitude]="place.point.lng"
    [label]="place.name[0]"
    (markerClick)="gm.lastOpen?.close(); gm.lastOpen = infoWindow">
    <agm-info-window #infoWindow>
        <strong>{{place.name}}</strong>
    </agm-info-window>
</agm-marker>

В новой версии 1.0.0-beta.0 - green-zebra AOT не работает:
Свойство lastOpen не существует для типа AgmMap

Что может быть?

Отлично работает, мое использование шаблона вызывает настраиваемую функцию щелчка, как в

(markerClick)="gm.lastOpen?.close(); gm.lastOpen = infoWindow; markerClicked(m);"

Привет,

Даже с решением @ Martin-B это не работает: /

Любая помощь ?

@ Martin-B огромное спасибо за решение. Работает удовольствие!

@ Martin-B Хорошее спасибо!
@melbouhy Позор мне; забыл добавить #infoWindow в <agm-info-window> . Может, вы сделали ту же ошибку?


public openIW (data = undefined) {
if (this.IW) {
this.IW.close ();
}

this.IW = data;

}

@ Martin-B, как использовать это ((markerClick) = "gm.lastOpen? .Close (); gm.lastOpen = infoWindow; markerClicked (m);") в agm-маркере, ответьте с кодом .ts

@menakav Вот
в файле .ts:
`
markerClicked (infoWindow) {
если (this.infoWindowOpened === infoWindow)
возвращаться;

    if(this.infoWindowOpened !== null)
    {
        this.infoWindowOpened.close();
    }

    this.infoWindowOpened = infoWindow;
}

in .html file: (markerClick) = "gm.lastOpen? .Close (); gm.lastOpen = infoWindow; markerClicked (m);" `

@menakav Ваш код мне не
:(

Я протестировал все коды на этом форуме, и моя проблема заключается в полученном здесь infoWindow :

  clickedMarker(infoWindow, index: number) {
    ...
  }

infoWindow всегда первый, независимо от того, сколько у меня очков. Всегда я получал infoWindow с _id = 0.

Параметр index получает истинный идентификатор нажатого маркера ....

Это мой html:

<agm-marker *ngFor="let point of points; let i = index" [latitude]="point.latitude"
                            [longitude]="point.longitude"
                            [iconUrl]="iconUrl" (markerClick)="clickedMarker(infoWindow, i)">
<agm-info-window [disableAutoPan]="true" #infoWindow *ngIf="!isDetailMovil">
        <div class="marker__tittle">{{point.name}}</div>

Есть идеи, почему всегда появляется одно и то же информационное окно?

Решение @soyersoyer "только шаблон" отлично работает. Однако, как только исходный массив agm-маркеров заменяется новыми элементами маркера (например, после обновления ajax), внезапно предыдущие информационные окна больше не закрываются автоматически. В чем может быть проблема?

@markschmid мой обходной путь при замене исходного массива agm-маркеров.
(markerClick)="tmp=gm.lastOpen;gm.lastOpen=infoWindow;tmp?.close();"

Мое решение, основанное на ответе @lauwrentius :

* .html

<agm-marker 
    *ngFor="let marker of markers; let i = index"
    (markerClick)="showInfoWindow(infoWindow, i)"
>
    <agm-info-window #infoWindow></agm-info-window>
</agm-marker>

* .ts

infoWindowOpened = null;

filter() {
    infoWindowOpened = null;
    // redraw the map with filtered markers
}

showInfoWindow(infoWindow, index) {
    if (this.infoWindowOpened === infoWindow) {
        return;
    }

    if (this.infoWindowOpened !== null) {
        this.infoWindowOpened.close();
    }

    this.infoWindowOpened = infoWindow;   
}

@JimmyTheNerd

Можете ли вы объяснить, как вы запускаете filter(){infoWindowOpened = null;} не выдавая в качестве ошибки 'не удается найти infoWindowOpened'? Это происходит после изменения массива значков маркеров.

Я решил проблему.
Я поделился кодом:
(markerClick) = "clickedMarker (infoWindow, point, point.latitude, point.longitude)">

clickedMarker (data = undefined, currentPoint: any, lat: string, lng: string) {
if (this.IW) {
this.IW.close ();
}
const details = data._infoWindowManager._infoWindows;
if (details.size> 0) {
details.forEach ((элемент, ключ) => {
if (key.hostMarker.latitude === lat && key.hostMarker.longitude === lng) {
this.IW = ключ;
}
});
}
}

Надеюсь, это поможет.

Спасибо.

Сб, 28 апр 2018, 02:04, Кристиан Эрнандес [email protected]
написал:

Я решил проблему.
Я поделился кодом:
[latitude] = "point.latitude" [longitude] = "point.longitude"
[iconUrl] = "iconUrl" (markerClick) = "clickedMarker (infoWindow, точка,
point.latitude, point.longitude) "> [disableAutoPan] = "true" * ngIf = "! isDetailMovil">

clickedMarker (data = undefined, currentPoint: any, lat: string, lng:
строка) {если (this.IW) {this.IW.close (); } const details =
data._infoWindowManager._infoWindows; if (details.size> 0) {
details.forEach ((element, key) => {if (key.hostMarker.latitude === lat &&
key.hostMarker.longitude === lng) {this.IW = key; }}); }}

Надеюсь, это поможет.

-
Вы получаете это, потому что вас упомянули.
Ответьте на это письмо напрямую, просмотрите его на GitHub
https://github.com/SebastianM/angular-google-maps/issues/797#issuecomment-385086695 ,
или отключить поток
https://github.com/notifications/unsubscribe-auth/AgIM0TGCgyHK-snaJdIlSZSQuq0MF1Ihks5ts4DDgaJpZM4LQ0M7
.

Вот мое решение. Работает с угловым 6.
HTML:

<agm-marker *ngFor="let marker of markers" [latitude]="marker.latitude"[longitude]="marker.longitude" (markerClick)="markerClick(infoWindow)">
<agm-info-window #infoWindow>
</agm-info-window>
</agm-marker>

Машинопись:

lastSelectedInfoWindow: any;
markerClick(infoWindow: any) {
        if (infoWindow == this.lastSelectedInfoWindow) {
            return;
        }
        if (this.lastSelectedInfoWindow != null) {
         try{
            this.lastSelectedInfoWindow.close();
          } catch {} //in case if you reload your markers
        }
        this.lastSelectedInfoWindow = infoWindow;
    }

После долгих исследований и неясных решений наконец-то получилось прекрасное решение для очистки предыдущего окна agm-info при открытии нового.

Это мой component.html:

 <agm-map (mapClick)="close_window($event)" [fullscreenControl]='true' [mapTypeControl]='true' [latitude]="lat" [longitude]="lng" [zoom]="13" [scrollwheel]="false">
     <div *ngFor="let data of zonas">
        <agm-marker (markerClick)=select_marker(infoWindow) [latitude]="data.latitud" [longitude]="data.longitud">
           <agm-info-window #infoWindow >            
           </agm-info-window>
         </agm-marker>
      </div>
  </agm-map>

А это мой component.ts:

constructor(public apiService: ApiService) {}
infoWindowOpened = null
previous_info_window = null
...
close_window(){
if (this.previous_info_window != null ) {
  this.previous_info_window.close()
  }    
}

select_marker(data,infoWindow){
 if (this.previous_info_window == null)
  this.previous_info_window = infoWindow;
 else{
  this.infoWindowOpened = infoWindow
  this.previous_info_window.close()
 }
 this.previous_info_window = infoWindow
}

Таким образом, каждый раз, когда открывается новое окно, оно обнаруживает событие и закрывает предыдущее, также это работает для закрытия открытого окна, если пользователь щелкает за пределами окна в любой другой части карты.

Спасибо @JimmyTheNerd , у меня это сработало!

Мое решение, основанное на ответе @lauwrentius :

* .html

<agm-marker 
    *ngFor="let marker of markers; let i = index"
    (markerClick)="showInfoWindow(infoWindow, i)"
>
    <agm-info-window #infoWindow></agm-info-window>
</agm-marker>

* .ts

infoWindowOpened = null;

filter() {
    infoWindowOpened = null;
    // redraw the map with filtered markers
}

showInfoWindow(infoWindow, index) {
    if (this.infoWindowOpened === infoWindow) {
        return;
    }

    if (this.infoWindowOpened !== null) {
        this.infoWindowOpened.close();
    }

    this.infoWindowOpened = infoWindow;   
}

Спасибо @JimmyTheNerd , все работает.

Эта проблема была автоматически помечена как устаревшая, поскольку в последнее время не было активности. Он будет закрыт, если больше не будет активности. Спасибо за ваш вклад.

Была ли эта страница полезной?
0 / 5 - 0 рейтинги