简体   繁体   中英

Iterating over an array and adding google maps event to each?

so I have a project that's working with Google Maps, using KnockoutJS. I define the markers like so:

for (i = 0; i < markerData.length; i++) {
  // Grab marker data so we only have to call it once
  var m = markerData[i];
  // Define everything
  var position = new google.maps.LatLng(m.location.lat, m.location.lng);
  var title = m.title;
  // etc etc

  // Push all this info to the google maps marker
  var marker = new google.maps.Marker({
    map: map,
    position: position,
    title: title
    // etc with rest 
  });

And then in the same for loop, I try to define an info window, simplified for reading:

  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(this.title + '<br>' + this.address + '<br><a target="_blank" href="' + this.directions + '">Get Directions</a>');
    infoWindow.open(map, this);
    map.setCenter(this);
  });

While it works exactly as I like it, linters are saying not to make a function inside the for loop. With that being said - is there a way I can move this outside the for loop and still get it to work effectively? Everything I've tried thus far has essentially turned into another for loop in one way or another, which still fires up the linter.

I feel like I'm missing something blatantly apparent here. Any thoughts or ideas to how I can properly apply this?

As a side note - all markers are in the KO vm viewModel.gMarkers() . Greatly appreciate any help, thanks!

Specifically the linter is complaining about the anonymous function google.maps.event.addListener(marker, 'click', function() {}; within the for loop. You could try putting it into its own function and calling it within the loop with the marker passed in.

var m, position, title, marker;

for (i = 0; i < markerData.length; i++) {
  // Grab marker data so we only have to call it once
  m = markerData[i];
  // Define everything
  position = new google.maps.LatLng(m.location.lat, m.location.lng);
  title = m.title;
  // etc etc

  // Push all this info to the google maps marker
  marker = new google.maps.Marker({
    map: map,
    position: position,
    title: title
    // etc with rest 
  });

  doThis(marker);
}

function doThis(marker) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(this.title + '<br>' + this.address + '<br><a 
    target="_blank" href="' + this.directions + '">Get Directions</a>');
    infoWindow.open(map, this);  // Not sure where map is coming from
    map.setCenter(this);
 });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM