Question

I'm trying to set up a relatively simple info window using google maps api. I want to put multiple variables into my info window from my django backend. If I only include one variable it works fine. However, if I try to include multiple variables then nothing is rendered. I cannot figure out why. This is the offending line:

'<h1 id="infolayer-title" class="firstHeading">{{ variable1 }} {{ variable2 }}</h1>'+

However, this works fine, strangely:

'<h1 id="infolayer-title" class="firstHeading">{{ variable1 }}</h1>'+

The variables are being properly rendered in the markup, but there is a javascript error. The javascript console says SyntaxError: missing ; before statement on the line printed above, but including a semicolon before or after the variable has not solved the problem.

Here is the full implementation (most of which is straight from the maps api docs):

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
  var myLatlng = new google.maps.LatLng(122, 5);
  var mapOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var contentString = '<div id="content">'+
      '<div id="infolayer">'+
      '</div>'+
      '<h1 id="infolayer-title" class="firstHeading">{{ variable1 }} {{ variable2 }}</h1>'+
      '<div id="bodyContent">'+
      '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
      'Heritage Site.</p>'+
      ...
      '</div>'+
      '</div>';

  var infowindow = new google.maps.InfoWindow({
      content: contentString
  });

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Hello World!'
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });
 }

google.maps.event.addDomListener(window, 'load', initialize);

How can I get the map to render using multiple variables in the Info Layer Window? Thanks for any ideas that may help with this confusing problem!

Was it helpful?

Solution

The apostrohpe in SomeDude's is acting as the end of the contentString for that line, then there is more content after it. You need to escape this variable, which should happen by default so maybe you turned off autoescaping? Try replacing with this:

'<h1 id="infolayer-title" class="firstHeading">{% autoescape on %}{{ variable1 }} {{ variable2 }}{% endautoescape %}</h1>'+

It will encode the ' in SomeDude's as &#39; for a rendering of SomeDude&#39;s which will not break your string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top