我正在尝试使用API和HTML5地理位置,根据Google地图中模型中存储的纬度和经度放置标记。
问题是如何使用模板关键字循环遍历JavaScript标记中存储的每个对象的lat / lon信息,我认为不能在Django中完成。
我在Adding Google Map Markers with DJango Template Tags in Javascript发现了一个类似的问题,我稍加修改并将其放在模板中 - 而不是单独的脚本文件 - 但它似乎不起作用:
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 %}
}
有关如何使用lat,lon信息正确循环存储的Django对象中的项目以及使用API将这些项目放置在Google Map上的任何见解都将非常感激。
答案 0 :(得分:9)
我使用django-geoposition来管理我的地理数据
from django.db import models
from geoposition.fields import GeopositionField
class Zone(models.Model):
name = models.CharField(max_length = 50 )
kuerzel = models.CharField(max_length = 3 )
kn_nr = models.CharField(max_length = 5 )
beschreibung = models.CharField(max_length = 300 )
adresse = models.CharField(max_length = 100 )
position = GeopositionField()
<强> view.py 强>
from geo.models import Zone
from django.shortcuts import render_to_response, get_object_or_404, redirect
def ShowZonen(request):
zone=Zone.objects.all()
return render_to_response('zonen.html', {"zone": zone})
def showZoneDetail(request, zone_id):
zone=Zone.objects.get(id=zone_id)
return render_to_response('zonendetail.html', {"zone": zone})
<强>模板强> zonendetail.html
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var mapDiv = document.getElementById('map-canvas');
map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(48.208174,16.373819),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
}
function addMarkers() {
{% for mark in zone %}
var point = new google.maps.LatLng({{mark.position.latitude}},{{mark.position.longitude}});
var image = '{{ STATIC_PREFIX }}'+ 'checkmark.png';
var marker = new google.maps.Marker({
position: point,
map: map,
icon: image,
url: 'http://172.16.0.101:8882/zone/' + {{mark.id}},
title: '{{ mark.id }}',
});
marker['infowindow'] = new google.maps.InfoWindow({
content: "<h1>{{mark.name}}</h1> <br> {{ mark.name }} <p> <a href=\"http:\/\/172.16.0.101:8882\/zone\/{{ mark.id }}\"> {{ mark.name }}</a>",
});
google.maps.event.addListener(marker, 'click', function() {
//window.location.href = this.url;
this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseover', function() {
// this['infowindow'].open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
// this['infowindow'].close(map, this);
});
{% endfor %}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>