{"id":1036,"date":"2022-08-30T15:11:19","date_gmt":"2022-08-30T15:11:19","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/09\/dynamicaly-adding-infowindows-and-markers-on-google-maps-v3-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:11:19","modified_gmt":"2022-08-30T15:11:19","slug":"dynamicaly-adding-infowindows-and-markers-on-google-maps-v3-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/dynamicaly-adding-infowindows-and-markers-on-google-maps-v3-collection-of-common-programming-errors\/","title":{"rendered":"Dynamicaly adding InfoWindows and Markers on Google Maps V3-Collection of common programming errors"},"content":{"rendered":"<p>I am having a very annoying issue with Google Map V3 JavaScript API. The problem might be related to my JavaScript code though.<\/p>\n<p>Here is my complete code:<\/p>\n<pre><code>\n    var __mvcGoogleMap;\n    var __mvcGeocoder;\n    var markersArray = [];\n    var infoWindowsArray = [];\n\n    function _initializeGoogleMap() {\n\n        __mvcGeocoder = new google.maps.Geocoder();\n\n        var latlng = new google.maps.LatLng(38.98569417582484, 35.351452857849154);\n\n        var myOptions = {\n            zoom: 6,\n            center: latlng,\n            mapTypeId: google.maps.MapTypeId.HYBRID,\n            panControl: true,\n            zoomControl: true,\n            mapTypeControl: true,\n            scaleControl: true,\n            streetViewControl: false,\n            overviewMapControl: true\n        };\n        __mvcGoogleMap = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n    }\n\n    function findOnMap() { \n\n        var srchVal = $(\"#txtMapSearch\").val();\n\n        __mvcGeocoder.geocode({'address': srchVal}, function(results, status) {\n\n            if (status == google.maps.GeocoderStatus.OK) {\n\n                actionURL = '\/accommodation\/HotelsForMap';\n                actionData = 'lat=' + results[0].geometry.location.lat() + '&amp;lng=' + results[0].geometry.location.lng();\n\n                var _latLongs = [];\n                var _infoWindows = [];\n\n                $.ajax({\n                    type: \"POST\",\n                    url: actionURL,\n                    data: actionData,\n                    success: function (r) {\n\n                        if (markersArray) {\n                            for (i in markersArray) {\n                                markersArray[i].setMap(null);\n                            }\n                            markersArray.length = 0;\n                        }\n\n                        for (var i = 0; i &lt; r.length; i++) {\n\n                            _latLongs.length = 0;\n                            _infoWindows.length = 0;\n\n                            _latLongs[i] = new google.maps.LatLng(r[i].LatLong.Latitude, r[i].LatLong.Longitute);\n\n                            addMarker(_latLongs[i], r[i].Title);\n                            addInfoWindow(r[i].InfoWindow.Content, markersArray[i]);\n                            google.maps.event.addListener(markersArray[i], 'click', function() {\n\n                                infoWindowsArray[i].open(__mvcGoogleMap, markersArray[i]);\n                            });\n                        }\n\n                        var _currentPossition = results[0].geometry.location;\n                        __mvcGoogleMap.setCenter(_currentPossition);\n                        __mvcGoogleMap.setZoom(14);\n                    }\n                });\n            } else {\n                alert(\"Geocode was not successful for the following reason: \" + status);\n            }\n        });\n    }\n\n    function addMarker(location, title) {\n        marker = new google.maps.Marker({\n            position: location,\n            title: title,\n            map: __mvcGoogleMap,\n            draggable: false\n        });\n\n        markersArray.push(marker);\n    }\n\n    function addInfoWindow(content, marker) { \n\n        infoWindow = new google.maps.InfoWindow({\n            content: content\n        });\n        infoWindowsArray.push(infoWindow);\n    }\n\n    $(function() { \n        $.getScript('http:\/\/maps.google.com\/maps\/api\/js?sensor=false&amp;callback=_initializeGoogleMap', function() { \n            $(window).load(_initializeGoogleMap);\n        });\n    });\n\n    $(\"#btnMapSearch\").click(function() { \n        findOnMap();\n    });\n\n<\/code><\/pre>\n<p>Here is the situation: what I am trying to do is that after I initialize the map and search for a place, I get that places LatLang values and send it to my server. Then I get the results back from my server with some hotel info (name, lat, lang, etc).<\/p>\n<p>Then, I set the marker proper places and I attach infoWindow to each marker. Everything works fine except for infoWindows.<\/p>\n<p>When I click a marker, I see this error on browser console window:<\/p>\n<blockquote>\n<p>Uncaught TypeError: Cannot call method &#8216;open&#8217; of undefined<\/p>\n<\/blockquote>\n<p>Can you please have a look at what I am doing wrong here?<\/p>\n<ol>\n<li>\n<p>You will need to create a closure for the value of <code>i<\/code> so that it is assigned to the enclosed variable at the time each anonymous function is created. If not, as you continue through the loop, the value of <code>i<\/code> will change until the loop exits and it is left holding a value that is the length of your array + 1 (which is always an undefined index), and this is the <code>i<\/code> to which all of your anonymous functions refer. Try the following in your AJAX callback loop:<\/p>\n<pre><code>google.maps.event.addListener(markersArray[i], 'click', (function(idx) {\n    return function() {\n        infoWindowsArray[idx].open(__mvcGoogleMap, markersArray[idx]);\n    };\n})(i));\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-09 23:17:03. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I am having a very annoying issue with Google Map V3 JavaScript API. The problem might be related to my JavaScript code though. Here is my complete code: var __mvcGoogleMap; var __mvcGeocoder; var markersArray = []; var infoWindowsArray = []; function _initializeGoogleMap() { __mvcGeocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(38.98569417582484, 35.351452857849154); var myOptions [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1036","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1036","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=1036"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1036\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=1036"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=1036"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=1036"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}