Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda