javascript - Google maps add multiple markers and info windows for each one? -
i have code this:
function algolia_search(position) { clearoverlays(); var application_id = 'psh...vakl'; var search_only_api_key = '2eb...efa8'; var index_name = 'entities'; var params = { hitsperpage: 150 }; // client + helper initialization var algolia = algoliasearch(application_id, search_only_api_key); var algoliahelper = algoliasearchhelper(algolia, index_name, params); // map initialization algoliahelper.on('result', function(content) { renderhits(content); var i; // add markers map (i = 0; < content.hits.length; ++i) { var hit = content.hits[i]; var infowindow = new google.maps.infowindow({ content: hit.name }); var marker = new google.maps.marker({ position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng}, map: map, label: hit.name, animation: google.maps.animation.drop, index: }); marker.addlistener('click', function() { infowindow.open(map, marker); }); addlisteneronpoint(marker); markers.push(marker); infos.push(infowindow); } }); function renderhits(content) { $('#container').html(json.stringify(content, null, 2)); } algoliahelper.setqueryparameter('aroundradius', 200); algoliahelper.search(); }
now markers works absolutely fine, info windows doesn't. no matter marker click, shows me info windows 1 marker, don't know how solve it.
explanation of problem
the infowindow shows data 1 markerbecause when click on them call:
infowindow.open(map, marker);
at point clicked, waht think values infowindow
,map
, marker
respectively?
your assumption hold values set as loop running.
what happening for loop has finished running completely time click on the marker. values of infowindow
, marker
happen set last value of loop.
suggested solution(s)
the solution find way encapsulate data each iteration of loop persist when listener called.
two ways use es6 block scoped let
instead of var
or use n iife (immediate invoked function expression) encapsulate state of infowindow
, marker
each step of loop.
using
let
:for(i = 0; < content.hits.length; ++i) { // rest of code above --^ let infowindow = new google.maps.infowindow({content: hit.name}); let marker = new google.maps.marker({...}); marker.addlistener('click', function() { infowindow.open(map, marker); }); // rest of code below --v }
the above works because happens new variable created each
infowindow
,marker
variable each iteration, almost creating new vairable name each iteration(marker0
,marker1
, etc)
using iife:
for(i = 0; < content.hits.length; ++i) { // rest of code above --^ var infowindow = new google.maps.infowindow({content: hit.name}); var marker = new google.maps.marker({...}); function(inf, mar){ marker.addlistener('click', function() { inf.open(map, mar); })(infowindow, marker); } // rest of code below --v }
Comments
Post a Comment