javascript - One of my variables is being set in initMap, but when I call another function inside the script that same variable is suddenly undefined -


i original had question posted, wouldn't let me edit post nor resign in. in hope have refocus , make clear asking for.

i define map in callback function of google maps api. initmap being called first. once manually trigger addvehiclemarker method.

this how being called in html side:

// index.html  <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initmap"></script> <script defer src="../src/map-manager.js"></script> 

this doing in initmap below:

// map-manager.initmap  map = new google.maps.map(document.getelementbyid('map'), {     zoom: 15,     center: home_latlng,     streetviewcontrol: false }); 

my issue

i want import map-manager.js class elsewhere. addvehiclemarker method. when following...

var mapmanager = require('../src/map-manager'); mapmanager.addvehiclemarker(v); 

map in map-manager.js undefined. when do...

addvehiclemarker(v); 

map in map-manager.js has map defined in initmap. without having import file.

question

how can achieve same thing in addvehiclemarker(v); while allowing import , called mapmanager.addvehiclemarker(v);, while retaining map?

this rest of source:

// map-manager.js  var vehiclemanager = require('../src/vehicle-manager'); var wamptasks = require('../src/wamp-tasks');  var map; var vehiclemarkers = [];  function initmap() {     const home_latlng = {         lat: 33.816714399999995,         lng: -117.90523610000001     };      map = new google.maps.map(document.getelementbyid('map'), {         zoom: 15,         center: home_latlng,         streetviewcontrol: false     }); }  // http://blog.mridey.com/2010/03/using-markerimage-in-maps-javascript.html function addvehiclemarker(vehicle) {     console.log(map);     var icon = new google.maps.markerimage(         vehicle.iconlocation,         null, /* size determined @ runtime */         null, /* origin 0,0 */         null, /* anchor bottom center of scaled image */         new google.maps.size(32, 32)     );     var marker = new google.maps.marker({         position: vehicle.currentlatlng,         icon: icon,         map: map     });     console.log(marker);     // marker.settitle(string(vehicle.displayname));      vehiclemarkers.push(marker);     console.log(vehiclemarkers); }  module.exports = {}; module.exports["addvehiclemarker"] = addvehiclemarker; 

seems var scope issue. declare var map @ window level (and remove if presente other nested var maps; delacration

<script>   var map;   map = new google.maps.map(document.getelementbyid('map'), {     zoom: 15,     center: home_latlng,     streetviewcontrol: false  });  .... </script> 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -