I know this is a common question, and I'm a JS newbie, but I'm completely stumped even after searching StackOverflow for hours.
I'm using the Google Maps API, and want to keep track of my markers by association with an ID. So I have var pinArray = new Object()
as a global variable, and add markers like this:
function CreateMarkers (data){
data.forEach(function(store) {
<!-- CREATE MAP MARKER -->
var mapLat = store.latitude;
var mapLong = store.longitude;
var mapLatLng = { lat: parseFloat(mapLat), lng: parseFloat(mapLong) };
var marker = new google.maps.Marker({
position: mapLatLng,
title: store.name,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: 'Green',
fillOpacity: 0.8,
strokeWeight: 0.6,
},
zIndex: 0
});
cluster.addMarker(marker);
var key = store.Id;
pinArray['${key}'] = marker;
})
}
Where cluster
is var cluster = new MarkerClusterer(map);
.
When I try to do console.log(pinArray);
back outside of the function, I get an empty object: Object {}
. I've tried not using string interpolation as well, like pinArray[store.Id] = marker;
, but get the same problem.
I need to keep this global associate between pins and IDs because I need to reference and update markers by their ID in other functions. Or at least, I think I do, I'm open to other ways of doing this. Help is very much appreciated; thank you in advance.
Typically when I've done something like this in the past I'll use a standard javascript array instead of an ID'd object:
var pinArray = [];
Then use push to add the markers to it as you go:
pinArray.push(Marker);
When you create the pin you can include your key in its property definition:
var marker = new google.maps.Marker({
position: mapLatLng,
title: store.name,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 8.5,
fillColor: 'Green',
fillOpacity: 0.8,
strokeWeight: 0.6,
},
zIndex: 0,
key: store.Id
});
and you can write a simple looping lookup function to find the individual map marker if you need to pull them by ID. Something like:
function GetMarkerByKey(key) {
var i = 0;
while (pinArray[i].key != key) {i++}
return pinArray[i];
}
Also, if you're using it in a dynamic event handler for click or hover you can use the this property to identify which marker they are activating it with.
~~~Edited to fix a syntax error~~~
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With