Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
Can't access variable from within a function's scope

I have this script to create google maps with markers template inside my Django project:

<script>
  function initMap() {

    const shop = {
      lat: 45.0203018,
      lng: -88.318316
    };

    const map = new google.maps.Map(
      document.getElementById("map"), {
        zoom: 10,
        center: shop,
    });  
  
    const vehicles = {{ vehicles|safe }};
    for(i = 0; i < vehicles.length; i++){
      const pos = new google.maps.LatLng(vehicles[i]['lat'],vehicles[i]['lon']);
      const marker = new google.maps.Marker({
        position: pos,
        map: map,
        label: vehicles[i]['number'],
      }); 
    
      const id = vehicles[i]['truck']     
      marker.addListener("click", () => {
        console.log(id)
        window.location = "{% url 'invent:truck' id %}";
      });  
    };   
  };

  window.initMap = initMap;
</script>

But it doesn't see variable id inside the addListener function. And if I put the variable inside the function it doesn't see the vehicles variable. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Figured it out:

const id = vehicles[i]['truck']
const url = "{% url 'invent:truck' 1234 %}".replace(/1234/, id.toString());
marker.addListener("click", () => {
  window.location = url
});  
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!