我正在尝试从我的数据库中检索lat long值并在googlemap上将它们可视化。我不确定如何使用for循环访问这些字段
models.py
import json from django.db
import models from django.utils.translation
import ugettext_lazy as _
class LocateGoose(models.Model):
class Meta:
app_label = 'My Goose'
verbose_name = _('Where is the Goose?')
external_id = models.IntegerField(unique=True)
latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True)
name = models.TextField(max_length=250, null=True, blank=True)
address = models.TextField(max_length=25, null=True, blank=True)
views.py
from edrive.mygoose.models import LocateGoose
from django.shortcuts import render
def testgmap(request):
data = LocateGoose.objects.all()
template = 'hereismygoose.html'
return render(request, template, {"data": data})
hereismygoose.html中的Javascript
function initMap() {
var myLatLng = {lat: 52.0116, lng: 4.3571};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'stringLocate me!'
});
map.setOptions({ minZoom: 4, maxZoom: 10 });
}
答案 0 :(得分:1)
在视图中创建纬度和经度的列表,并将其发送到上下文中的模板。
import json
def testgmap(request):
data = LocateGoose.objects.values('name', 'latitude', 'longitude')
json_data = json.dumps(list(data))
return render(request, 'hereismygoose.html', {"data": json_data})
现在在你的initMap()
函数循环中的html中。
var locations = {{data|safe}};
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['latitude'], locations[i]['longitude']),
map: map,
title: locations[i]['name']
});
}