I am rewriting a legacy JS code. We have a bundled minified JS an no original source code.
The code below uses google maps V3 to create markers. For the next step (marker cluster), I would need to access mapInstance.map which currently is undefined. I am unable to figure out why the mapInstance.map is not accessible from outside its function.
Would really appreciate if someone could point me where I went wrong.
var mapInstance;
// calling create map
window.initMap = function(){
// code to get lat/long
var items
const options = {
markerIcon: `/images/map-marker.png`
};
const mapOptions = {
center: { lat, lng },
zoom: zoom,
scrollwheel: true,
streetViewControl: false,
mapTypeControl: false
};
mapInstance = createMap(options, mapOptions);
mapInstance.init();
addMarkers(items); // uses foreach mapInstance.addMarkers() to add markers to map
console.log(mapInstance.map); // fails to get map object
console.log(mapInstance.markers); // successfully gets markers []
console.log(mapInstance.getMapObject()); //can retrieve map object with this style
}
This function handles task related to google maps.
function createMap (options, mapOptions) {
const mapEl = document.getElementById("MapView");
var map = undefined;
var bounds;
var markers = [];
const defaultOptions = {
markerIcon: undefined,
onBoundsChanged: () => { },
onMarkerClick: () => { }
};
const defaultMapOptions = {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 10,
scrollwheel: false
};
const mergedOptions = _.assignIn({}, defaultOptions, options);
const mergedMapOptions = _.assignIn({}, defaultMapOptions, mapOptions);
function init() {
map = new google.maps.Map(mapEl, mergedMapOptions);
map.addListener("bounds_changed", mergedOptions.onBoundsChanged);
console.log(map);
};
function getMapObject() {
return map;
}
const addMarker = (id, title, latitude, longitude) => {
const position = new google.maps.LatLng(latitude, longitude);
const marker = new google.maps.Marker({
id: id,
position: position,
map: map,
title: title,
icon: mergedOptions.markerIcon ? mergedOptions.markerIcon : undefined
});
marker.addListener("click", () => {
mergedOptions.onMarkerClick(marker);
});
marker.setMap(map);
markers.push(marker);
};
// other functions not related to this issue.
return {
mapEl,
map,
markers,
bounds,
init,
getMapObject,
addMarker,
clearAllMarkers,
panTo,
panToMarker,
selectMarker,
deSelectMarker,
setZoom,
getZoom,
resetZoom,
getMarker,
fitBoundsToMarkers,
fitBoundsToVisibleMarkers
};
};