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

如何在Google Maps信息窗口的a标签href和内容中插入变量?

你当前代码的核心问题是拼接信息窗口内容字符串时,<a>标签未被正确识别为字符串片段,变量插值和字符串拼接逻辑混淆导致渲染出错。推荐使用ES6模板字符串统一处理内容拼接,语法更简洁不容易出现拼接错误,修正后代码如下:

function showDetails(placeResult, marker, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    let placeInfowindow = new google.maps.InfoWindow();
    let rating = "None";
    if (placeResult.rating) rating = placeResult.rating;
    let placeResultStringArray = placeResult.formatted_address.split(",");
    // 对地址参数做编码处理,避免地址包含特殊符号/空格导致链接失效
    let lurl = `https://bajablast.live/${encodeURIComponent(placeResultStringArray[0].trim())}`;
    // 统一用模板字符串拼接所有内容,无需拆分零散字符串做+拼接
    placeInfowindow.setContent(`
      <div>
        <strong>${placeResult.name}</strong><br>
        <a href="${lurl}">
          ${placeResultStringArray[0]},${placeResultStringArray[1]},${placeResultStringArray[2]}
        </a><br>
        Rating: ${rating}
      </div>
    `);
    placeInfowindow.open(marker.map, marker);
    currentInfoWindow.close();
    currentInfoWindow = placeInfowindow;
    // showPanel(placeResult);
  } else {
    console.log("showDetails failed: " + status);
  }
}

如果你需要沿用原本的+拼接写法,只需要把<a>标签部分正确包裹为字符串即可,对应修改setContent部分代码:

placeInfowindow.setContent(
  "<div><strong>" +
    placeResult.name +
    "</strong><br>" + 
    '<a href="' + lurl + '">' +
    placeResultStringArray[0]+","+placeResultStringArray[1]+","+placeResultStringArray[2]+
    "</a>" +
    "<br>" +
    "Rating: " +
    rating +
    "</div>"
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:48:03