JoshGumby87
JoshGumby87

Reputation: 9

Google Maps API JS Marker - Django

In Django, I am trying to populate the google maps api by rendering the template with info from views.

I can get the results to return to the template however I am having difficulty implementing it into the javascript tag with Django. Any suggestions.

I would like the django data to return into the addmarker function in JS

Python - Django Views

    def maps_multi(request):

        address_list = CustomerOrder.objects.filter(city__icontains = 'CA').distinct() # pulls all unique addresses in California
        address_list1 = address_list[0:3] # temporarily select first three addresses from list to test

        geolocator = GoogleV3()

        add_list=[]
        for x in address_list1:
            add_city = x.city
            location = geolocator.geocode(add_city)
            add_list.append(location)
            print(add_list)

        context = {'location': add_list}

        return render(request, 'orderdisplay/maps_multi.html', context)

//JAVASCRIPT

      // New map
      var map = new google.maps.Map(document.getElementById('map'), options);


      // INSERT Lat Lng via django here
      addMarker({coords:{lat:33.6846, lng:-117.8265}});
      addMarker({coords:{lat:34.0522, lng:-118.2437}});
      addMarker({coords:{lat:33.9533, lng:-117.3962}});



      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position: props.coords,
          map:map,
          icon:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
        });

       }
    }
  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=*****&callback=initMap">
    </script>

Upvotes: 0

Views: 1200

Answers (1)

dentemm
dentemm

Reputation: 6379

I assume your js code is placed within your orderdisplay/maps_multi.html template. Then you can simply do this:

// New map
var map = ...

// INSERT Lat Lng via django here

{% for location in add_list %}
    addMarker({coords:{
        lat: {{ location.latitude|stringformat:'f' }}, 
        lng: {{ location.longitude|stringformat:'f' }}
        }
    });
{% endfor %}

Upvotes: 2

Related Questions