user8817894
user8817894

Reputation:

adding multiple markers on GoogleMaps

I am trying to retrieve the lat long values from my db and visualise them on googlemap. I'm not sure how do I access those fields using for loop

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

Javascript in hereismygoose.html

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

Upvotes: 1

Views: 2422

Answers (1)

Satendra
Satendra

Reputation: 6865

Create a list of latitude and longitude in your views and send it to template in context.

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

Now in your html inside your initMap() function loop over it.

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']
    });
}

Reference: Google Maps Simple Multiple Marker

Upvotes: 1

Related Questions