Adding Google Map Markers with Django Template Tags in Javascript

I am trying to add a bunch of map markers to a map using the Django template tag variables like latitude and longitude, but it doesn’t work so well. Here is what I have in the presentation of javascript code. I am loading the code as an external JS file. Here is what I need to initialize everything. Also, when I did this, the google map didn't even display anymore. He disappeared.

 function initialize() {
            var latLng = new google.maps.LatLng(41.85, -87.65);

            map = new google.maps.Map(document.getElementById('map_canvas'), {
                zoom: 8,
                center: latLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });



             marker = new google.maps.Marker({
                position: latLng,
                title: 'Point A',
                map: map,
                draggable: true
            });

            // Update current position inf o and load in markers from database
            loadMarkers();
            updateMarkerPosition(latLng);
            geocodePosition(latLng);

And here is what loadMarkers () looks like

            function loadMarkers(){
            {% for mark in latest_marks %}
            var point = new google.maps.LatLng({{mark.lat}},{{mark.lng}});
                var marker = new google.maps.Marker({
                position: point,
                map: map,
            });
            {% endfor %}    
        }

Any help would be greatly appreciated. Greetings.

+3
source share
2 answers

You cannot put Django template tags inside external javascript files. Django doesn't even see these. Your web server serves clients directly.

, Django Javascript , . <script> , javascript .

. Django:

<script>var myVar = {something: 42};</script>

javascript myVar. , javascript.

, , : map: map,. script.

+3

, javascript-, google- api. javascript: , dict python ecmascript, :

python , javascript .

python:

{ 
   'position': point, 
   'map': map, 
}

javascript :

{ 
   position: point, 
   map: map, 
}

.

- JavaScript. Chrome , Firefox firebug ( IE ). , javascript , .

[]

django, javscript django, .

urls.py, javascript:

      (r'jsresources/latest_points.js', 'yourappname.views.latest_points') 

yourappname/views.py - :

def latest_points(request):
    latest_points = YourPointsModel.objects.order_by('-id')[100]
    return render_to_response('latest_points.js', locals(), mimetype='text/javascript')
+2

All Articles