将Django变量传递到Google Maps javascript

时间:2015-03-02 07:24:59

标签: javascript django

我可以将包含相关数据的位置列表返回到Django表单中。此代码以django形式将running_list显示为文本。

{% for running in running_list %}
<div class="eventholder">
 <div class="event_running">
        <div class="event-contents">
            <p><b>Crew number: {{ running.team }}</b></p>   
            <p><b>Site Address & Job No:</b> {{ running.event.name }}</p>
            <p><b>Coords:</b> {{ running.coords }}</p>
            <p><b>Job Type:</b> {{ running.event.job_type }}</p>
            <p><b>Field personnel name:</b> {{ running.owner }}</p>
            <p><b>Crew contact number:</b> {{ running.owner.phone_number }}</p>
        </div>
    </div>
</div>

{%endfor%}

好了,我现在想要在javascript var位置插入相同的变量列表。

   var locations = [
  ['NSW 01 Wadalba, 201-237 Figtree Blvd - 594094', -33.201016, 151.484362],
  ['NSW 02 Cessnock, Lot 702, 43 Trebbiano Dr - 616388', -33.023586, 151.557490],
  ['NSW 03 Redhead, 34 Burns St - 619553', -32.927678, 151.713359],
  ['NSW 04 Maitland, Bulwer St', -32.702620, 151.408145],
  ['NSW 05 Cameron Park, 4 Seacrest Dr - 591516', -33.059075, 151.657199]
];

这是完整的谷歌地图脚本。

  <script type="text/javascript">
var locations = [
  ['NSW 01 Wadalba, 201-237 Figtree Blvd - 594094', -33.201016, 151.484362],
  ['NSW 02 Cessnock, Lot 702, 43 Trebbiano Dr - 616388', -33.023586, 151.557490],
  ['NSW 03 Redhead, 34 Burns St - 619553', -32.927678, 151.713359],
  ['NSW 04 Maitland, Bulwer St', -32.702620, 151.408145],
  ['NSW 05 Cameron Park, 4 Seacrest Dr - 591516', -33.059075, 151.657199]
];

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(-32.927191, 151.520385),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

1 个答案:

答案 0 :(得分:1)

您可以在包含所需数据的视图中创建location_json var。

import json

location_json = json.dumps([
    [running.event.name, running.coords.latitude, running.coords.longitude] for running in running_list
])

然后在模板中:

var locations = {{ location_json|safe }};