Pointfield with geodjango, javascript and google maps

空扰寡人 提交于 2019-12-11 08:36:33

问题


I'm trying to display and plot a line from lattitude and longitude points stored in my database. Heres my code (I've removed some nonessential variables for brevity)

Here is my model:

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)

And here is my views:

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}, )

Here is the problem: this is the initalise function of my index.html. The coordinate list is a list of type point, such that it will loop through and output the lat and long points into the array. The problem is that somehow the array is not being accepted as a valid path in google maps. The function is copied mostly from the Google maps developer 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);

My question is, what is wrong with the {% for position in coordinate_list %} such that it does not generate a valid array that can be passed into google maps?

I'd really appreciate any help.


回答1:


You defined path as an object:

var path = {};

It should be defined as an array:

var path = [];

Update: It seems that LatLng() is called with one parameter only. It expects two numbers. ) is at wrong place.

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

should be changed to

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

See also example at jsbin.



来源:https://stackoverflow.com/questions/23077089/pointfield-with-geodjango-javascript-and-google-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!