I have the following JS:
Meteor.startup(function () {
map = L.map('map_canvas').locate({setView: true, maxZoom: 21});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
bounds = {};
map.on('locationfound', function(e){
bounds.bottomLeftLat = map.getBounds()._southWest.lat;
bounds.bottomLeftLng = map.getBounds()._southWest.lng;
bounds.topRightLat = map.getBounds()._northEast.lat;
bounds.topRightLng = map.getBounds()._northEast.lng;
console.log(bounds);
});
console.log('outside function: '+bounds);
});
My first console.log outputs correctly the 4 object properties with their values in the console, but the outside function log outputs an empty object, and when I try to access bounds outside of Meteor.startup then it's not even defined. I understand that functions limit the scope of variables but if bounds is defined outside the anonymous function, without 'var', isn't it considered to be a global?
- Why can I access 'map' but not 'bounds' outside of Meteor.startup?
- How could I rewrite this code by following more smart patterns (module?) so that I can both make bounds available in other parts of the script and successfully add the four properties as I am attempting?
edit the event is fired - after manually firing it, I still get an empty object:
map.fire("locationfound");
Object {type: "locationfound", target: e, bottomLeftLat: 50.05008477838258, bottomLeftLng: 0.384521484375, topRightLat: 51.63847621195153…}
MainClient.js:12
e {options: Object, _container: div#map_canvas.leaflet-container leaflet-fade-anim, _panes: Object, _mapPane: div.leaflet-map-pane, _tilePane: div.leaflet-tile-pane…}
bounds
Object {}