You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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_components array—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_id for reliability.

内容的提问来源于stack exchange,提问作者user8207054

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:22:16