How to create a custom InfoWindow with Google Maps and JavaScript?

Creating a custom InfoWindow in Google Maps JavaScript API allows you to customize the appearance and behavior of the default InfoWindow.

For example we write:

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Custom InfoWindow</title>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }

        .custom-info-window {
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
    <script>
        function initMap() {
            const map = new google.maps.Map(document.getElementById('map'), {
                center: {lat: 40.7128, lng: -74.0060},
                zoom: 12
            });

            const infowindow = new google.maps.InfoWindow({
                content: '<div class="custom-info-window">Custom InfoWindow Content</div>'
            });

            const marker = new google.maps.Marker({
                position: {lat: 40.7128, lng: -74.0060},
                map: map,
                title: 'Marker Title'
            });

            marker.addListener('click', function() {
                infowindow.open(map, marker);
            });
        }
    </script>
</body>
</html>

In this example, we should replace "YOUR_API_KEY" with your actual Google Maps API key.

We’ve added a <div> element with id "map" to hold the map.

In the CSS, we’ve added some styles for the custom InfoWindow, such as background color, padding, border-radius, and box-shadow.

In the JavaScript, we initialize the map and create a custom InfoWindow using the google.maps.InfoWindow class.

We set the content property to the HTML content that you want to display inside the InfoWindow.

We create a marker on the map and attach a click event listener to it. When the marker is clicked, we open the custom InfoWindow with the infowindow.open() method, passing the map and marker as parameters.