Django 1.11: Dynamic Javascript to load Google Map markers

Viewed 624

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

In my maps.js, I currently 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 e.g.

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

Currently I have a maps.js static file, which I load using:

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

I can't insert the tags there, because it's called statically. However, since maps.js is static, I can't load tags such as {{ listing.location }} , {{ listing.lat }} , {{ listing.lng }} etc.

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

1) I tried loading the a small

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

but this didn't work, I think because locationData is a function, which is also defined in maps.js.

I could possibly include the whole of maps.js in template.html, but it's 230 lines of code.

2) I tried adding maps.js to my users app folder, as so:

users/templates/users/maps.js

And inside that js I loaded template tags defined above. In my views.py I did:

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>

However, I get the error that the file couldn't be found.

2 Answers

Load your static file in the same manner:-

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

For passing values such as {{ model.location }} , {{ model.lat }} , {{ model.lng }} to your js file, save them as global variable in script tag in your HTML page as,

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

And refer them in maps.js by location lat and lng.

Further on to pass an array of data you can do it somewhat like this,

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

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

                {% endfor %}
            ];

Hope this Helps :-)

This could help you. when you put in context some structure and then render it in template with "safe" filter

Related