Why Not
Why Not

Reputation: 611

Placing Django Template Tags in Script Tags For Google Map Markers

Having a very frustrating time solving this issue. I have a model which automatically stores a user's latitude and longitude. I'm trying to use that information to place markers on a Google Map for each instance of that model. Seems simple enough. Using JavaScript appears the simplest way and Django template tags can apparently be placed within script tags as long as these are on the template. Looping through the model, though, doesn't appear to be working. There's likely just a simple error here but my JavaScript is weak and Firebug illustrating what exactly is wrong.

Is something simple missing? Perhaps there's a better way to do this through a specific Django view or a Python wrapper that works better for this purpose? Any insight or expertise is greatly appreciated.

Here's the page:

{% extends 'base.html' %}

{% block page_title %}Stentorian{% endblock %}
{% block headline %}Stentorian Storyline{% endblock %}

 {% block content %}

<div class="row">
    <div class="span12">

        <h2>Welcome <a href="{% url profiles_profile_detail user.username %}">{{ user.username }}</a></h2>
<br />
                       <div id="map_canvas" style="width: 300px; height: 200px; border-right: 1px solid #666666; border-bottom: 1px solid #666666; border-top: 1px solid #AAAAAA; border-left: 1px solid #AAAAAA;"></div>
<br />

        <div class="accordion" id="story_accordion">


        {% for story in stories %}
            <div class="accordion-group">
                <div class="accordion-heading">
                    <a class="accordion-toggle story-header" data-toggle="collapse" data-parent="#story_accordion" href="#story_{{ story.id }}">
                        {{ story.author }} - {{ story.title }} - {{ story.date }}
                    </a>
                </div>
                <div id="story_{{ story.id }}" class="accordion-body collapse{% if forloop.counter0 == 0 %} in{% endif %}">
                         <div class="accordion-inner">
                            <!-- <h2><a href="{% url detail story.id %}">{{story.title}}</a></h2>-->
                             <span><a href="{% url profiles_profile_detail story.author.username %}}">{{story.author}}</a> </span><br>

                            <span>{{story.topic}}</span><br>
                            <span>{{story.zip_code}}</span><br>

                            <span>{{story.date}}</span><br>

                            <p>{{story.copy}}</p>
                        </div>
                    </div>
                </div>

                <br>



            {% endfor %}
            </div>

        </div>
    </div>
<script>
function mainGeo()
    {
         if (navigator.geolocation) 
            {
              navigator.geolocation.getCurrentPosition( mainMap, error, {maximumAge: 30000, timeout: 10000, enableHighAccuracy: true} );
        }
        else
        {
              alert("Sorry, but it looks like your browser does not support geolocation.");
        }
    }




    var map;



     function mainMap(position)
     {
           // Define the coordinates as a Google Maps LatLng Object
           var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

           // Prepare the map options
           var mapOptions =
          {
                      zoom: 15,
                      center: coords,
                      mapTypeControl: false,
                      navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
                      mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            // Create the map, and place it in the map_canvas div
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            // Place the initial marker
            var marker = new google.maps.Marker({
                      position: coords,
                      map: map,
                      title: "Your current location!"
            });
        }


function error() {
            alert("You have refused to display your location. You will not be able to submit stories.");
        }

mainGeo();

function loadMarkers(){
             {% for story in stories %}
            var point = new google.maps.LatLng({{story.latitude}},{{story.longitude}});
            var marker = new google.maps.Marker({
            position: point,
            map: map
        });
        {% endfor %}    
    }

loadMarkers();
    </script>
    {% endblock content %}

Upvotes: 0

Views: 810

Answers (1)

undefined
undefined

Reputation: 6461

I'm no Django expert, but generally when you find yourself using your server-side code to generate javascript code, there's a better way -- either by making an AJAX call to load the data you need, or at least defining the data up at the top of your script, then placing the client-side logic after.

//set up a method on your model that returns your markers in JSON format,
//then load via ajax using jQuery or another library
$.get('/path/to/getMapMarkers', loadMarkers);

//or use the template to define it on the page so it looks like this
var stories = [{latitude:123.345,longitude:45.567},
    {latitude:123.345,longitude:45.567},
    {latitude:123.345,longitude:45.567}];

loadMarkers(stories);

//then either way, your function could look like this:
function loadMarkers(stories){
    for (var s in stories){
        var story = story[s];
        var point = new google.maps.LatLng(story.latitude, story.longitude);
        var marker = new google.maps.Marker({position: point, map: map}});
    }
}

This won't change the behavior of your code, but will clean it up and provide better code separation and make it easier to fix. Post your generated javascript if you still need more help.

Upvotes: 1

Related Questions