Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

Google Maps Markers: Object being ignored when looping through javascript array

I'm having some javascript issues working with the Google Maps javascript API on my site...

Essentially, I have this code:

// map defined elsewhere
// icon defined elsewhere

requests = some_array_of_requests;
markers = [];

requests.forEach((request) => {
if (some_bool)
{
   const marker = new google.maps.Marker({
      map,
      icon,
      position: { lat: some_float, lng: another_float },
   });
   markers.push( marker );
}
else
{
   const marker = new google.maps.Marker({
      map,
      icon,
      position: some_google_place_result.geometry.location,
      // also tried:
      // position: { lat: some_google_place_result.geometry.location.lat(), lng: some_google_place_result.geometry.location.lng() },
   });
   markers.push( marker );
}

for (var i = 0, len = markers.length; i < len; i++) 
{
   let marker = markers[i];
   google.maps.event.addListener(marker, "click", function ()
   {
      // add content to infowindow
   }
}

However, when I loop through the markers, all of the markers that have been added to the array in the else clause are being ignored, e.g. they are not being looped through...

When I console.log markers, I can see that it does contain the markers that have been pushed in the else clause, and the reported length also takes them into account. But when i console.log markers.length, the markers from the else clause are not being counted....

Does anybody have any idea as to what I'm missing?

question from:https://stackoverflow.com/questions/65936688/google-maps-markers-object-being-ignored-when-looping-through-javascript-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...