Google Map InfoWindow headerContent无法渲染HTML内容,显示为纯文本问题求助
Hey Fabrizio, let's sort out why your styled header isn't rendering properly in the Google Maps InfoWindow!
First off, the core issue here: the official Google Maps JavaScript API's InfoWindow doesn't actually have a headerContent parameter. It sounds like you might have come across outdated documentation (from an older API version like v2) or a third-party library's extension, not the current v3 API we use today. That's why your HTML is showing up as plain text—the API doesn't recognize headerContent at all, so it's just being ignored entirely.
Here's the Correct Approach
To add a styled header section to your InfoWindow, you'll need to build the full content (header + any body content) as a single HTML string (or DOM element) and pass it to the standard content parameter. The API fully supports HTML here, so your styling will render as expected.
Let's adjust the official simple InfoWindow example you referenced to include your red "Hello World!" header:
function initMap() { const myLatlng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatlng, }); // Create the InfoWindow with custom header + body content const infowindow = new google.maps.InfoWindow({ content: ` <div style="color:#ff0000; padding-bottom: 8px; border-bottom: 1px solid #ccc;">Hello World!</div> <div>Default example content goes here</div> `, }); // Create marker and attach click listener const marker = new google.maps.Marker({ position: myLatlng, map, title: "Click to open InfoWindow", }); marker.addListener("click", () => { infowindow.open({ anchor: marker, map, shouldFocus: false, }); }); }
Why This Works
- The
contentparameter is the official, supported way to pass all content to an InfoWindow, and it handles HTML strings, DOM elements, or Text nodes seamlessly. - You can structure your content with divs, custom styling, and valid HTML to create distinct header and body sections—exactly what you tried to do with the non-existent
headerContentparameter. - The InfoWindow will automatically adjust its size to fit your custom content, just like the documentation described for the (unofficial)
headerContentparameter.
Quick Note If You Were Using a Third-Party Library
If you thought you were using a library like InfoBox (a popular custom InfoWindow extension) that does support headerContent, double-check that you've included the library correctly and are following its syntax. But for the standard Google Maps InfoWindow, the method above is the right solution.
Give this a shot, and your red styled header should render perfectly instead of showing up as plain text!
内容的提问来源于stack exchange,提问作者Lode

