Django 1.11: Dynamic Javascript for loading Google Map markers

I need to dynamically insert data markers (name, latitude, long) in javascript, maps.js.

In my maps.js, I have:

var locations = [
        [ locationData('listings1.html','images/listing-item-01.jpg',"listing name",'Address ', '4.5', '12'), 40.94401669296697, -74.16938781738281, 1, '<i class="im im-icon"></i>'],
        [ locationData('listings2.html','images/listing-item-02.jpg','Name2','Place', '5.0', '23'), 40.77055783505125, -74.26002502441406,          2, '<i class="im im-icon"></i>'],];

And I need to be able to load this dynamically using a for loop, for example.

{% if listings %}
var locations = [
{% for listing in listings %}
[ locationData({{ listing.url}} , {{ listing.name }} , {{ listing.place }}) ],
{% endfor %}
]

I currently have a static maps.js file that I upload with:

<script type="text/javascript" src="{% static 'scripts/maps.js' %}"></script>

I cannot insert tags there because it was called statically. However, since maps.js- static, I cannot load tags such as {{ listing.location }} , {{ listing.lat }} , {{ listing.lng }}etc.

I tried 2 solutions (and described in the comments).

1) I tried loading a small

#template.html
<script>
var locations = 
// python code
</script>

but it didn’t work, I think, because it locationDatais a function that is also defined in maps.js.

maps.js template.html, 230 .

2) maps.js users, :

users/templates/users/maps.js

js , . views.py :

def index(request):
    js_file = "users/templates/users/maps.js" 

    return render(request, "users/template.html", context={"js_file": js_file })

#template.html

<script src="{{js_file}}"></script>

, .

+4
2

: -

<script type="text/javascript" src="{% static 'scripts/maps.js' %}"></script>

, {{ model.location }} , {{ model.lat }} , {{ model.lng }}, js, script HTML,

var location = "{{ model.location }}";
var lat = "{{ model.lat }}";
var lng = "{{ model.lng }}";

maps.js location lat lng.

, , :

 var locationsArray = [
                {% for location in locations %}

                    {
                        id: {{ location.pk }}, name: '{{ location.name|escapejs }}',
                        lat: '{{ location.lat }}',
                        lng: "{{ location.lng }}"
                    },

                {% endfor %}
            ];

, : -)

+2
+1

Source: https://habr.com/ru/post/1686051/


All Articles