Trying to implement "shouldFocus" infoWindowOpen Option in Google Maps API

Viewed 903

Can someone provide a simple example of "shouldFocus" boolean option to be used in Javascript when using the infoWindow.open method in Google Maps infoWindow?

InfoWindowOpenOptions interface

...

infoWindow.open(map, marker); // Open infoWindow but do not change focus to it - How to?

...

2 Answers

When calling open, you don't need to provide the map if you're going to specify the options object. It will render the window on the map the MVCObject (Marker, etc) is on.

infoWindow.open({
    anchor: marker,
    shouldFocus:false
});

This will prevent the InfoWindow from being focused.

EDIT 2

I have retested it with the Version 3.43 (which will be deleted in mid-august) and it still works. So imho this is a bug introduced in Version 3.44 when also the property shouldFocus has been introduced.

There currently are issues open that describe the problem: https://issuetracker.google.com/issues/190075886 https://issuetracker.google.com/issues/190637181

EDIT

I just created a fiddle in which the given method does not work under a couple circumstances. I cannot reproduce why this happens. I have created a fiddle which opens a given InfoWindow after 2.5 seconds and 5 seconds.

Case 1: After 2.5 seconds, the InfoWindow is opened, but not focused. If the InfoWindow is closed immediately after opening it, it is not being focused after 5 seconds.

Link to case 1 fiddle: https://jsfiddle.net/ywnj6bc4/5/

Case 2: If after 2.5 seconds the InfoWindow is opened but not closed, the InfoWindow is being focused after 5 seconds.

Link to case 2 fiddle: https://jsfiddle.net/ywnj6bc4/4/

I am still searching for a proper workaround for my case as I have not yet discovered what exactly produces this – in my opinion – wrong result.

Original answer

I just struggled with the very same problem. Mainly because I was using the InfoWindow without a marker associated to it.

My Workaround was creating the InfoWindow, and then opening it by adding a "fake" marker as the anchor option.

There would probably be other ways of achieving this as stated in the docs:

If anchor is non-null, position this InfoWindow at the top-center of the anchor, instead of at the given latlng. The InfoWindow will be rendered on the same Map or StreetView as the anchor.

See this code example.

var map = new google.maps.Map({some: options})

let infoWindow = new google.maps.InfoWindow({
  content: 'Info Window Content...',
  position: {lat: 47.5, lng: 8.5},
});

infoWindow.open({
  shouldFocus: false, 
  anchor: new google.maps.Marker({
    anchor: infoWindow.position, // same position as infoWindow
    map: map
  })
});
Related