Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow.

Answer №1

If you want to incorporate event listening in your code, consider using the google.maps.event.addListener:

In the browser, JavaScript operates on events, meaning it responds to interactions by producing events and expects a program to pay attention to these events. There are two main types of events:

  • User events (like "click" mouse events) that transfer from the DOM to the Google Maps JavaScript API. These events differ from standard DOM events.
  • MVC state change notifications which reflect changes in Maps JavaScript API objects and follow a convention named property_changed.

Every Maps JavaScript API object provides various named events. Programs interested in specific events can register JavaScript event listeners for those events and execute relevant code when the events occur by utilizing addListener() to attach event handlers on the object.

You may also refer to this sample code mentioned in this post:

var geocoder;
var map;

function initialize() {
    var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
        center: new google.maps.LatLng(37.4419, -122.1419),
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

setMarkers(map,locations);


}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
  ['Bondi Beach', -33.890542, 151.274856,,, 'Bondi Beach', 4],
  ['Coogee Beach', -33.923036, 151.259052,,,'Coogee Beach', 5],
  ['Cronulla Beach', -34.028249, 151.157507,,,'Cronulla Beach', 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187,,, 'Manly Beach', 2],
  ['Maroubra Beach', -33.950198, 151.259302,,,'Maroubra Beach', 1]
];
function setMarkers(map, locations) {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < locations.length; i++) {
        var item = locations[i];

        var myLatLng = new google.maps.LatLng(item[1], item[2]);
        bounds.extend(myLatLng);
        var address = item[5];

        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
        });

        var content = address;

        var infowindow = new google.maps.InfoWindow()

        google.maps.event.addListener(marker, 'mouseover', (function (marker, content, infowindow) {
            return function () {
                infowindow.setContent(content);
                infowindow.open(map, marker);
            };
        })(marker, content, infowindow));
        google.maps.event.addListener(marker, 'mouseout', (function (marker, content, infowindow) {
            return function () {
                infowindow.close();
            };
        })(marker, content, infowindow));

    }
    map.fitBounds(bounds);
}

This code snippet is available on jsfiddle. It should function properly if your event listener does not clash with other listeners.

I hope this explanation proves beneficial.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guess the Number Game with while Loop

I have a project where I need to limit guesses to 10, display the guessed number, and keep those results on the screen after each game without replacing the previous guesses. Each set of guesses should be numbered to show how many guesses have been made us ...

Ways to showcase a JSON menu with a single level

I have a json file containing links to all the images in a specific folder, as shown below: ["http://img1.png","http://img2.png","http://img3.png","http://img4.png"] I would like to create a <ul> list using this data, but I'm not sure how to d ...

Thorax.js bower installation issue

After following the instructions in this guide: https://github.com/walmartlabs/thorax-seed/blob/master/README.md, I ran into an unexpected issue on my Windows machine. When running npm start It seems like bower is doing a lot of work (presumably loading ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

Utilizing jQuery to dynamically add results and prevent duplicate entries in will_paginate

I am currently using will_paginate to easily manage the comments pagination in my Rails 3 application, and so far it's been working flawlessly. At the moment, I have set up the display to show 10 comments per page. However, whenever I add a new comme ...

Ancient queries carry the weight of time

Extremely ancient, very old, incredibly aged beyond belief ...

Switching up icons using React Spring - a step-by-step guide!

Is it possible to change the icon when I click on it using react spring? For example, if I click on " ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

React Switch not displaying various pages correctly

After creating a new component to switch between pages on my React app, I encountered an issue where the HomePage renders correctly when entering the site, but clicking on navlinks does not work. Additionally, when trying to access the url /contacto, ins ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Looping through elements using JQuery in groups of 2

Let's say I have the following array: Mike Blue Jakob Red Luis Orange and I'm using this JQuery code to loop through it: $.each( arr, function( index, value ){ $( ".div" ).append( "" + value + "" ); } }); Now, I want to modify the ...

Scrolling jqgrid to focus on the current day column and implementing a blinking effect on cells with stored data

I have a jqgrid with 38 columns of data, where the first 6 columns are frozen and the rest are unfrozen. Depending on the combo box selection, it shows either dates or months (see sample image here). After loading the grid, I want it to automatically scrol ...

The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the ...

Error with infiniteCarousel in Internet Explorer versions 7 and 8 when using jQuery

Hello everyone! I've run into a little issue with some jQuery code I'm using. It was working fine before, but after making several changes and improvements, I can't seem to figure out what the problem is. I keep getting JS errors in both IE7 ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Establish initial content for the specified div area

I need help setting page1.html to display by default when the page loads. Can you provide some guidance? Appreciate your assistance in advance. <head>     <title>Test</title>     <meta http-equiv="content-type" content="tex ...

Please enter only numerical values using jQuery

Currently, I am facing a slight issue. My goal is to only run the code when the input characters are numbers. This is the snippet of code I have been working with: $(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .j ...

How to use hooks in NETXJS to pass data from a page to a component

Hey there, how are you doing? I am currently working on a project using Next.js and styled components. I am trying to change a string using props in my layout component, where the main content is dynamic per page. Page 'prueba.js' import React f ...

Dynamic Selection List Population in jqGrid

Using jqGrid 4.13.3 - free jqGrid In the Add form, there is a static input element and a select list element. The keyup ajax function is bound to the input element using dataEvents in the beforeInitData event. Once the Add form is displayed, entering a va ...

Creating a dynamic multi-select feature in AngularJS with ng-repeat

I'm relatively new to AngularJS and JavaScript, but I've managed to create a functional multi-select list. The ng-model linked to the dropdown is part of a "user" DTO object, specifically a property that stores an array of "groups" the user can j ...