如何为Google Maps API标记设置带换行地址并使用信息窗样式
Fixing Google Maps InfoWindow Address Formatting & Styling
Alright, let's get your Google Maps InfoWindow looking proper with a nicely formatted, line-broken address and the standard Google Maps styling. Here's the adjusted code for the section after the // display window on the Map comment:
google.maps.event.addListener(marker, 'click', function() { // Extract address components from the place object for dynamic, accurate formatting const street = place.address_components.find(comp => comp.types.includes('route'))?.long_name || ''; const postalCode = place.address_components.find(comp => comp.types.includes('postal_code'))?.long_name || ''; const city = place.address_components.find(comp => comp.types.includes('locality'))?.long_name || ''; const country = place.address_components.find(comp => comp.types.includes('country'))?.long_name || ''; // Build content with standard InfoWindow-friendly HTML structure const infoContent = ` <div> <b>${place.name}</b><br> ${street ? `${street}<br>` : ''} ${postalCode && city ? `${postalCode} ${city}<br>` : ''} ${country ? country : ''} <div class="view-link"> <a target="_blank" href="https://www.google.de/maps/place/${place.place_id}"> <span>In Google Maps ansehen</span> </a> </div> </div> `; infowindow.setContent(infoContent); infowindow.open(map, this); });
Key Improvements:
- Dynamic Address Extraction: Instead of hardcoding the address, we pull real data from the
place.address_componentsarray—this ensures the address is always accurate for the place ID you're using. - Proper Line Breaks: Each address segment (street, postal code + city, country) gets its own line, with conditional checks to avoid empty lines if a component is missing.
- Standard Styling: Google's InfoWindow automatically applies its default styling to clean HTML structures like this, so you'll get the native Google Maps look without extra custom CSS.
- Cleaner Link: We replaced the hardcoded link with one using the
place.place_idfor reliability.
内容的提问来源于stack exchange,提问作者user8207054
相关产品推荐
相关产品推荐

