Search code examples
javascriptgoogle-maps-api-3infowindow

How to put a variable as a href and variable text inside it? (Google maps info window)


I am having trouble figuring out how to put dynamic links inside my google maps info window, and also wrapping some dynamic text with tags.

How can I pass lurl to the a href, and place placeResultStringArray[0]+","+placeResultStringArray[1]+","+placeResultStringArray[2]+ inside the tags?

Here is the code that I am working with:

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/${placeResultStringArray[0]}`;
    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);
  }
}

Solution

  • Replace

    <a href = ${lurl}> +
    

    with

    `<a href="${lurl}">` +
    

    ...or with

    "<a href=\"" + lurl + "\">" + 
    

    ...or with

    "<a href='" + lurl + "'>" + 
    

    You also need to wrap </a> in quotes, as you want it parsed as string, not as a javascript expression (which would result in an error).

    Until you get to the point where you can easily figure out the output of a string concatenation, the easiest way to figure out what's wrong is to console.log() the current value and modify your code until the logged string is the desired result.

    Most likely, your setContent should look like this:

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

    which I would write as:

    placeInfowindow.setContent(`
    <div>
      <strong>
        ${placeResult.name}
      </strong>
      <br>
      <a href="${lurl}">
        ${[0,1,2].map(i => placeResultStringArray[i]).join(',')}
      </a>
      <br>
      Rating: ${rating}
    </div>
    `);
    

    I find it easier to read/understand, hence modify.