An array of infoWindow in Google maps api

2019-03-06 15:21发布

问题:

I looked for error and I couldn't find it. Any google maps infoWindow always shows the same information for some reason.

Here is a coffeescript code

infowindow = new google.maps.InfoWindow()
for company in companiesData
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(company.latitude, company.longitude)
    map: map
  })

  #debugger ---> each company.name is different!
  google.maps.event.addListener(marker, 'click', ()->
    infowindow.setContent(company.name)
    infowindow.open(map,this)
  )

I debugged it and saw that each company.name was different.

The output javascript

  infowindow = new google.maps.InfoWindow();
  _results = [];
  for (_j = 0, _len1 = companiesData.length; _j < _len1; _j++) {
    company = companiesData[_j];
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(company.latitude, company.longitude),
      map: map
    });
    _results.push(google.maps.event.addListener(marker, 'click', function() {
      infowindow.setContent( company.name);
      return infowindow.open(map, this);
    }));
  }
  return _results;
});

So where is an error?

回答1:

you need to obtain closure on the variable company. You can do that by creating your markers in a separate function. for example:

infowindow = new google.maps.InfoWindow()
for(var n = 0 ; n < n companiesData.length ;n++){
  createMarker(companiesData[n]);
}

function createMarker(data){
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude)),
    map: map
  })

  #debugger ---> each company.name is different!
  google.maps.event.addListener(marker, 'click', function(){
    infowindow.setContent(data.name);
    infowindow.open(map,this);
  }
  )
}

Explanation here.



回答2:

I had the same... try to create marker in separate function. It helped for me.

Check it out: https://developers.google.com/maps/articles/phpsqlsearch_v3

Find code with "searchLocationsNear(center)" function.