I am trying to access variables set at the "window" level (I believe). I am able to reference these in all functions, but when I try to reference it in a event listener function, the values are undefined. In the below code, the lat and lng values are undefined.
<script>
let map;
let lat;
let lng;
let location_name;
let travel_radius;
let circleObject;
const source = document.getElementById('travel-radius-value');
function inputHandler(e) {
console.log('old travel_radius: ' + this.travel_radius);
this.travel_radius = e.target.value;
console.log('updated travel_radius: ' + this.travel_radius);
let lat = this.lat; //<-UNDEFINED
let lng = this.lng; //<-UNDEFINED
circleObject.setMap(null);
circleObject = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillColor: "#FF0000",
fillOpacity: 0.35,
map,
center: {lat, lng},
radius: this.travel_radius*1000,
});
}
source.addEventListener('input', inputHandler);
Update: new code. lat and lng are still undefined
<script>
let map;
let lat;
let lng;
let location_name;
let travel_radius;
let circleObject;
const source = document.getElementById('travel-radius-value');
function inputHandler(e) {
console.log('old travel_radius: ' + this.travel_radius);
this.travel_radius = e.target.value;
console.log('updated travel_radius: ' + this.travel_radius);
circleObject.setMap(null);
circleObject = new google.maps.Circle({
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillColor: "#FF0000",
fillOpacity: 0.35,
map,
center: {lat, lng},
radius: this.travel_radius*1000,
});
}
source.addEventListener('input', inputHandler);
thisin your code refers to#travel-radius-value. Just use the name of the global variable to refer it. If it's shadowed by a local variable,window.lat/lng/travel_radiusis the way to go.window.foowill not let you access a variable declared withletlettovarand it's workingwindowobject is massively crowded, you can't remove globals, they're not garbage collected, they're exposing your data for easy manipulation (not that anything would be safe in JS in a browser), and you usually don't need globals at all.