使用GeoDjango、JavaScript和谷歌地图的点字段

2 投票
1 回答
796 浏览
提问于 2025-04-18 02:47

我正在尝试从存储在数据库中的经纬度点显示并绘制一条线。以下是我的代码(为了简洁,我去掉了一些不必要的变量)

这是我的模型:

class GpsLog(models.Model):

device=models.ForeignKey(Device,related_name="logs")
coordinates=models.PointField()

objects = models.GeoManager()
def __unicode__(self):
  return '%s %s ' % ( self.coordinates.x, self.coordinates.y)

这是我的视图:

def index(request):
device_table = DeviceTable(Device.objects.all(), prefix="1-")
gpsData_table = GPSDataTable(GpsLog.objects.all(), prefix="2-")
RequestConfig(request).configure(device_table)
RequestConfig(request).configure(gpsData_table)

coordinate_list = list(GpsLog.objects.all())

return render(request, 'index.html',
              {'table1': device_table, 'table2': gpsData_table, 'coordinate_list': coordinate_list}, )

这里是问题所在:这是我index.html的初始化函数。坐标列表是一个点的列表,它会循环遍历并将经纬度点输出到数组中。问题是,这个数组似乎没有被谷歌地图接受为有效路径。这个函数大部分是从谷歌地图开发者API复制过来的。

 function initialize() {
        var mapOptions = {
            zoom: 3,
            center: new google.maps.LatLng(0, -180),
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);


        var path = {};

        {% for position in coordinate_list %}
            path.push((new google.maps.LatLng({{ position.coordinates.x }}), {{ position.coordinates.y }}));


        {% endfor %}

        var tracking_map = new google.maps.Polyline({
            path: path,
            geodesic: true,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            strokeWeight: 2
        });

        tracking_map.setMap(map);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

我的问题是,{% for position in coordinate_list %} 有什么问题,以至于它没有生成可以传递给谷歌地图的有效数组?

我非常感谢任何帮助。

1 个回答

2

你把 path 定义成了一个对象:

var path = {};

其实应该把它定义成一个数组:

var path = [];

更新: 看起来 LatLng() 只用一个参数来调用,但它其实需要两个数字。) 的位置不对。

    path.push((new google.maps.LatLng({{ position.coordinates.x }}), {{ position.coordinates.y }}));

应该改成:

    path.push(new google.maps.LatLng({{ position.coordinates.x }}, {{ position.coordinates.y }}));

另外,可以查看 jsbin上的示例

撰写回答