FOR loop to iterate through array - javascript

I have an array that I would like to iterate through with a for loop to avoid excessive code. I would like to take the following:
var mySchool = document.getElementById(varID[0]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
and have it be more like:
for(var i=0; i < varID.length; i++){
var mySchool = document.getElementById(varID[i]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}
I've been doing some reading and i suspect it has something to do with Javascript closures but can't for the life of me get it to work with the various code examples i have found. I'm hoping the experienced eye can spot something i'm missing from this Javascript newbie.
My complete code looks like this:
//There are more items in my array but i wanted to keep it short here
var varID = [
"adamRobertson",
"blewett",
"brentKennedy"
];
var tableId = '1yc4wo1kBGNJwpDm6e-eJY_KL1YhQWfftjhA38w8';
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(49.491052,-117.304484),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, tableId, map);
//Trying to get this to work
for(var i=0; i < varID.length; i++){
var mySchool = document.getElementById(varID[i]);
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}
//Trying to avoid this 25 times
/*
google.maps.event.addDomListener(document.getElementById(varID[0]),
'click', function() {
filterMap(layer, tableId, map);
});
*/
}
// Filter the map based on checkbox selection.
function filterMap(layer, tableId, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: 'Location',
from: tableId,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var schools = document.getElementsByName('school');
for (var i = 0, school; school = schools[i]; i++) {
if (school.checked) {
var schoolName = school.value.replace(/'/g, '\\\'');
filter.push("'" + schoolName + "'");
}
}
var where = '';
if (filter.length) {
where = "School IN (" + filter.join(',') + ')';
}
return where;
}
google.maps.event.addDomListener(window, 'load', initialize);
The HTML basically contains input for checkboxes to turn my polygons on and off.
Thanks in advance for any help.

I think it will help if you change the code to this:
var mySchool; var limit = varID.length;
for(var i=0; i < limit; i++){
mySchool = document.getElementById(varID[i]);
(function(){
google.maps.event.addDomListener(mySchool,'click', function() {
filterMap(layer, tableId, map);
});
}());
}
I took the for limit calculation out of the loop so that will save some speed too.
I haven't used the maps api so you may have to add some arguments to the closure.
var mySchool; var limit = varID.length;
for(var i=0; i < limit; i++){
mySchool = document.getElementById(varID[i]);
(function(s, l, t, m){
google.maps.event.addDomListener(s,'click', function() {
filterMap(l, t, m);
});
}(mySchool, layer, tableId, map));
}
I'm not sure which args are needed, but you'll probably figure it out.

Related

Multiple markers with specific infotemplate content

When I'm looping through a list of addresses, I'm able to plot the markers for all the addresses fine. But when I click on any marker, the infowindow content shows data of only the last marker. How do I solve this?
Javscript
var map ={};
map.markers = [];
map.addresses = [
{
'line': '2101 K St',
'ref_no': '160621-000005'
},
{
'line': '2131 K St',
'ref_no': '170708-000015'
},
{
'line': '2321 K St',
'ref_no': '170707-000028'
}
];
.
.
.
map.map_object = new Map("esri_map", {
basemap: "topo",
center: [<lat>, <lng>],
zoom: 12
});
var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
for(var i = 0; i < map.addresses.length; i++)
{
var addr = map.addresses[i];
var params = {
countryCode: "US",
maxLocations: 1,
address: {"SingleLine": addr.line}
};
locator.addressToLocations(params, function(candidates){
locatorDone(candidates, addr);
});
}
function locatorDone(candidates, addr)
{
.
.
.
var html = "<h5>"+addr.line+"</h5>";
html += "<p>Ref#: "+addr.ref_no+"</p>";
var infoTemplate = new esri.InfoTemplate(addr.ref_no, html); // <--- Problem lies here
var graphic = new esri.Graphic(pt, symbol,'',infoTemplate);
map.map_object.graphics.add(graphic);
map.markers.push(graphic);
}
P.S: I've solved similar problems (in case of Google Maps API) by using closures. But I'm not sure how to use that in this case.
You can wrap the inside of the for loop in a self invoking function which will provide the closure. Something like this:
for(var i = 0; i < map.addresses.length; i++)
(function (i) {
var addr = map.addresses[i];
var params = {
countryCode: "US",
maxLocations: 1,
address: {"SingleLine": addr.line}
};
locator.addressToLocations(params, function(candidates){
locatorDone(candidates, addr);
});
})(i)
This will make i local to this code block. As it is now in your code all addr are referencing the last address because the for loop has finished running when you call locatorDone asynchronously. Alternatively you can use let like so: for (let i = 0; ... if you don't need this code to run on Internet Explorer below version 11.

Google maps api filter checkbox [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to make google map with filtering. One filter is select box (for now it is working) and other filer is with check boxes. So now my it have behavior as a radio button. You can se example here http://extrol.ellectadigital.com/distributeri/.
When you check it, it shows good pin, but when you click on the second it removes the first pin, and I don't want that.
So here is my code :
`http://codepen.io/PoznanM/pen/VpoZOm`
Problem is here onclick="filterChecker(this.value);" in filterChecker function only single checked item was compared and other marker are cleared.
So you have to compare all the checked items. I added function selectAllChecked() which passes checked values as array to function filterChecker()
var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
content: ''
});
var filters = {
shower: false,
vault: false,
flush: false
}
// Our markers
markers1 = [
['0', 'Title', 44.741318, 20.433573, 'Beograd', 'distributer'],
['1', 'Title', 45.823783, 16.024404, 'Zagreb', 'servis'],
['2', 'Title', 44.438350, 17.631215, 'Bosna', 'maloprodaja']
];
/**
* Function to init map
*/
function initialize() {
var center = new google.maps.LatLng(45.662477, 18.022074);
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.662477, 18.022074),
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
/**
* Function to add marker to map
*/
function addMarker(marker) {
var tip = marker[5];
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
tip: tip,
category: category,
map: map
});
gmarkers1.push(marker1);
// Marker click listener
google.maps.event.addListener(marker1, 'click', (function(marker1, content) {
return function() {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
/**
* Function to filter markers by category
*/
filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
var get_set_options = function() {
ret_array = []
for (option in filters) {
if (filters[option]) {
ret_array.push(option)
}
}
return ret_array;
}
var filter_markers = function() {
set_filters = get_set_options()
// for each marker, check to see if all required options are set
for (i = 0; i < markers.length; i++) {
marker = markers[i];
// start the filter check assuming the marker will be displayed
// if any of the required features are missing, set 'keep' to false
// to discard this marker
keep = true
for (opt = 0; opt < set_filters.length; opt++) {
if (!marker.properties[set_filters[opt]]) {
keep = false;
}
}
marker.setVisible(keep)
}
}
// Fuction for checkboxes
var tipovi = document.getElementsByClassName('chk-btn').value;
var selectAllChecked = function() {
var checkedPlace = []
var allCheckedElem = document.getElementsByName('filter');
for (var i = 0; i < allCheckedElem.length; i++) {
if (allCheckedElem[i].checked == true) {
checkedPlace.push(allCheckedElem[i].value)//creating array of checked items
}
}
filterChecker(checkedPlace) //passing to function for updating markers
}
var filterChecker = function(tip) {
//console.log(tip);
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
//console.log(marker);
if (in_array(this.marker.tip, tip) != -1) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
// Init map
initialize();
function in_array(needle, haystack) {
var found = 0;
for (var i = 0, len = haystack.length; i < len; i++) {
if (haystack[i] == needle) return i;
found++;
}
return -1;
}
#map-canvas {
height: 300px;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<div id="map-canvas">
</div>
<select id="type" onchange="filterMarkers(this.value);">
<option value="">Izaberite Mesto</option>
<option value="Beograd">Beograd</option>
<option value="Zagreb">Zagreb</option>
<option value="Bosna">Bosna</option>
</select>
<div id="buttons">
<input type="checkbox" name="filter" value="distributer" class='chk-btn' onclick="selectAllChecked();">
<label for='shower'>Distributer</label>
<input type="checkbox" name="filter" value="maloprodaja" class='chk-btn' onclick="selectAllChecked();">
<label for='flush'>Maloprodaja</label>
<input type="checkbox" name="filter" value="servis" class='chk-btn' onclick="selectAllChecked();">
<label for='vault'>Servis</label>
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCmUfKutqGZ-VgbD4fwjOFd1EGxLXbxcpQ&sCensor=false"></script>

Very slow loop in angularjs

I use this loop for create map markers (1000 points):
var markers = {};
for (var i = 0; i < items.data.data.length; i++) {
latVal = items.data.data[i].lat;
lngVal = items.data.data[i].lng;
ikona = icons.infost;
message = "<b>" + items.data.data[i].name + "</b>";
markers[i] = {'group': 'cmp', 'lat' : eval(latVal), 'lng' : eval(lngVal), 'icon' : ikona, 'message' : message};
}
$scope.Markers = markers;
how I can improve the for loop speed in angularjs (currently it takes almost 10s)?
Remove eval. It's slow and drops all browser optimizations for entire chain of functions.
Use array markers = [] instead of object.
Use + for converting string to number.
Use push to append elements to array.
Save items.data.data to a variable.
There is a few things that can improve your code speed like avoiding eval and caching loop variables and arrays as well. By caching some values, reduce a bunch of operations like member access and unecessary calculations.
var items = { data: { data: [] }};
var icons = { infost: 'infost'};
for (var i = 0; i < 1000; i++) {
items.data.data.push({ lat: ''+i, lng: ''+i, name:''+i });
}
console.time('time');
/// YOUR CODE STARTS HERE
var
data = items.data.data,
l = data.length,
markers = Array(l), // or just []
item, latVal, lngVal, ikona, message;
for (var i = 0; i < l; i++) {
item = data[i];
latVal = item.lat;
lngVal = item.lng;
ikona = icons.infost;
message = "<b>" + item.name + "</b>";
markers[i] = {
group: 'cmp',
lat: +latVal,
lng: +lngVal,
icon: ikona,
message: message
};
}
console.timeEnd('time');
//$scope.Markers = markers;

Google Map Condition on Town

I want a condition on my code where user input start point and end point, I want to make a check on start point to check that it is located in London or not so I find this code which work well in function but I want its variable town make function outside of this function so I create the checkpoint.
var input = document.getElementById('start');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// get town of selected place
function getTown(address_components) {
var geocoder = new google.maps.Geocoder(); result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
var town = getTown(place.address_components);
// if place is in London, move marker to the place
if (town == 'London') {
alert('in London');
} else {
// if not, do nothing and alert user
alert('you must click on a place in London');
}
});
How can I access var town outside of this function on whole page so I make condition on base of it?
You can make a variable outside of the scope of the callback to set the result to.
var input = document.getElementById('start');
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: {lat: 51.507351, lng: -0.127758}
});
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var town;
// when user has clicked on an autocomplete suggestion
google.maps.event.addListener(autocomplete, 'place_changed', function() {
function getTown(address_components) {
result = address_components;
var info = [];
for (var i = 0; i < result.length; ++i) {
if (result[i].types[0] == "locality") {
return result[i].long_name;
}
}
};
document.getElementById('place').innerHTML = '';
document.getElementById('town').innerHTML = '';
town = getTown(autocomplete.getPlace().address_components);
});
function inLondonCheck(placeName) {
document.getElementById('place').innerHTML = placeName + " in London? " + (town === 'London');
document.getElementById('town').innerHTML = town || '';
}
setInterval(function() {
if (town) inLondonCheck(autocomplete.getPlace().name);
}, 500);
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="start">
<div>Place<pre id="place"></pre></div>
<div>Town<pre id="town"></pre></div>
<div id="map-canvas"></div>

Javascript array element undefined in Google Maps API [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 8 years ago.
I am trying to add 3 markers to a map and when click on the markers, an info window will be shown. But every array element inside google.maps.event.addListener becomes undefined.
What's the problem?
<div id="map-canvas2" style="width:100%;height:500px"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var num;
var marker;
var infoWindow;
var infoText;
var lat;
var lng;
var map;
function initialize() {
num = 3;
marker = [];
infoWindow = [];
infoText = [];
lat = [];
lng = [];
infoText[0] = "test1";
lat[0] = 22.420845;
lng[0] = 114.208705;
infoText[1] = "test2";
lat[1] = 22.416026;
lng[1] = 114.209321;
infoText[2] = "test3";
lat[2] = 22.420841;
lng[2] = 114.205188;
for (var i = 0; i < num; i++) {
marker[i]=new google.maps.Marker({
position:new google.maps.LatLng(lat[i], lng[i]),
});
infoWindow[i] = new google.maps.InfoWindow({
content:"<div>"+infoText[i]+"</div>"
});
}
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(22.420458,114.207482)
};
map = new google.maps.Map(document.getElementById('map-canvas2'), mapOptions);
for (var i = 0; i < num; i++) {
marker[i].setMap(map);
google.maps.event.addListener(marker[i], 'click', function() {
new google.maps.InfoWindow({
content:"<div>"+infoText[i]+"</div>"
}).open(map,marker[i]);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
The problem:
Each event listener is referencing the same variable i which gets incremented on each pass of the for loop. So after the loop is finished the value of i is 3, but none of your arrays have an index of 3 so you get undefined. Because each event handler is referencing the same i variable they are all referencing the same undefined array values.
The solution: Create a closure so that the event handler for each marker has a it's own variable instead sharing reference to single variable.
for (var i = 0; i < num; i++) {
marker[i].setMap(map);
google.maps.event.addListener(marker[i], 'click', (function(index) {
return function() {
new google.maps.InfoWindow({
content: "<div>"+infoText[index]+"</div>"
}).open(map, marker[index]);
}
})(i));
}
What we're doing is creating a Immediately-Invoked Function Expression "IIFE". The IIFE has a parameter called index which is set to the value of i. Because variables have function scope, index belongs only to this function. Inside the IIFE we return a function that will do the actual work when the event is triggered, but it will reference index not i.
Don't send indexed parameters to an anonymous function:
for (var i = 0; i < num; i++) {
var mrk = marker[i];
var iwContent = infoText[i];
mrk.setMap(map);
google.maps.event.addListener(mrk, 'click', function() {
new google.maps.InfoWindow({
content:"<div>"+iwContent+"</div>"
}).open(map,mrk);
});
}

Categories

Resources