0

I'm trying to get data from a Django Backend to display on a map with Google Maps API, but I can't figure out how to pass the variables into the Javascript. Can someone please help me figure out what I'm doing wrong?

Django Method:

def home(request):
    //stuff that processes the method
    return render(request, 'map/index.html', {'lats': lats, "longs": longs, 'lat': lat, 'long': long, 'names': names, 'scores': scores})

HTML Snippet:

 <script> src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = ../../static/navbar.js></script>
    <!-- input tag-->


    <form method="post">
        {% csrf_token %}
        <input id="address" type="text" name="address">
        <input type="submit" style="display: none" />

    </form>

    <script>
        var names = {{ names }};
        var lats = {{ lats }};
        var longs = {{ longs }};
        var scores = {{ scores }};
        var lat = {{ lat }};
        var long = {{ long }};
    </script>

    <!-- this implements the map-->
    <div id="map"></div>
    <script src = ../../static/index.js> </script>

Javascript Snippet(index.js):

let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [names[count], lats[count], longs[count], scores[count]];
}
let curlat = lat, curlong = long;

1 Answer 1

1

Simply save the variable to window in your template:

<script>
    window.names = {{ names }};
    window.lats = {{ lats }};
    window.longs = {{ longs }};
    window.scores = {{ scores }};
    window.lat = {{ lat }};
    window.long = {{ long }};
</script>

Now in your js file:

let locations = new Array(names.length);
for(let count = 0; count < names.length; count++){
    locations[count] = [window.names[count], window.lats[count], window.longs[count], window.scores[count]];
}
let curlat = lat, curlong = long;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.