views:

13

answers:

1

I'm new to javascript so bear with me:

I'm implementing Google Maps API and I'd like the first marker's InfoWindow to open when the template is first rendered but ONLY if certain condition is true.

so, I have something like this:

{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
  var infowindow = new google.maps.InfoWindow({
    maxWidth:500
  });
  infowindow.setContent(markers[0].html);
  infowindow.open(map, markers[0]);
{% endif %}

which does NOT throw an error in FF and IE7, DOES what I want, but just SEEMS wrong. My text editor is screaming its head out.

Is this bad coding practise? And if so, any suggestions for the alternative?

Thanks beforehand


This is the complete code with the irrelevant bits edited out:

<script type="text/javascript">
function initialize() {
  ...
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  var markers = []
  setMarkers(map, projects, locations, markers);
  ...
}

function setMarkers(map, projects, locations, markers) {
  for (var i = 0; i < projects.length; i++) {
    var project = projects[i];
    var address = new google.maps.LatLng(locations[i][0],locations[i][1]);

    var marker = new google.maps.Marker({
            map: map, 
            position:address,
            title:project[0],
            html: description
        });

    markers[i] = marker;
    google.maps.event.addListener(marker, 'click', function() {
           infowindow.setContent(this.html);
              infowindow.open(map,this);
    });
  }

{% if project %}
//the following is automatically open the infowindow of the FIRST marker in the array when rendering the template
  var infowindow = new google.maps.InfoWindow({
    maxWidth:500
  });
  infowindow.setContent(markers[0].html);
  infowindow.open(map, markers[0]);
{% endif %}

 })
}

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

+1  A: 

There's nothing wrong with using a Django template tag inside a clump of Javascript. Django's templating language is for the most part language-agnostic: it doesn't care what the templated text means.

I've got rivers of Javascript with tons of tags, conditionals, variable substitutions, and so on.

Your other option for this sort of thing is to insert a Javascript boolean variable, and put the conditional in Javascript:

<script>
var is_project = {% if project %}true{% else %}false{% endif %};

//...

if (is_project) {
    // stuff for project
}
</script>

I suppose this keeps the Javascript cleaner. You'd have to decide based on your own code which style you prefer.

Ned Batchelder