zyeek zyeek - 22 days ago 10
Javascript Question

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 this question posted, but wouldn't let me edit post nor resign in. In this I hope to have refocus and make it clear what I am asking for.

I define my map in the callback function of Google Maps Api.

initMap
is definitely being called first. Once it is I manually trigger the
addVehicleMarker
method.

This is how it is 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 is what I am 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 to import my
map-manager.js
class elsewhere. Mainly for the
addVehicleMarker
method. When I do the following...

var MapManager = require('../src/map-manager');
MapManager.addVehicleMarker(v);


map
in
map-manager.js
is now undefined.
When I do...

addVehicleMarker(v);


map
in
map-manager.js
has the map which I defined in
initMap
. Without my even having to import the file.

Question



How can I achieve the same thing in
addVehicleMarker(v);
while allowing my to import it properly and called it as
MapManager.addVehicleMarker(v);
, while retaining
map
?

This is the rest of the 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 is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the 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;

Answer

Seems a var scope issue. Declare var map at 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