I generate some javascript from a php file. In this generated code, I create a multi-dimensional array and then populate it. The first nested array populates without problems but the second ones throws a TypeError: myArray[idx] is undefined.
Here's a code snippet:
function initialize() {
var arrayLabels = [];
var arrayMarkers = [];
var idx = 0;
arrayMarkers[idx] = [];
var mapLatlng = new google.maps.LatLng(40.6029248937, 7.7861327300);
var mapOptions = { center: mapLatlng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.SATELLITE };
var map = new google.maps.Map(document.getElementById("karte"), mapOptions);
var bounds = new google.maps.LatLngBounds();
arrayMarkers[idx]['breite'] = 44.4114053473682;
arrayMarkers[idx]['laenge'] = 8.91858100891113;
arrayMarkers[idx]['farbe'] = "http://new.kfb.localhost:8888/img/ico/button2_gruen.png";
arrayMarkers[idx]['hafen'] = "Ab/bis Genua";
arrayMarkers[idx]['link'] = "Karte, Wetter und<br>Landausflüge für<br><a href='hafen.php?hafen=172'>Genua</a><br>Sa, 16.03.13";
idx++;
arrayMarkers[idx]['breite'] = 43.3449053146323;
The error is thrown at the last line, right after the index has been incremented. Any ideas what the problem is?
Thanks
MK
You're incrementing idx, and then doing this:
arrayMarkers[idx]['breite'] = 43.3449053146323;
You've never put any object at arrayMarkers[idx], and so you end up trying to add a property to undefined, which causes an error.
If you want to create an array at the new index, add the second line shown here:
idx++;
arrayMarkers[idx] = []; // <=== Add this
arrayMarkers[idx]['breite'] = 43.3449053146323;
Side note: The things you're putting in arrayMarkers[idx] are arrays ([]), but you're not using them as arrays, you're using them as objects. You can do that in JavaScript (because those arrays aren't really arrays at all), but unless you're going to make use of the fact they're arrays, I'd just use objects:
arrayMarkers[idx] = {}; // Instead of []
idx++;
arrayMarkers[idx]['breite'] = 43.3449053146323;
should be
arrayMarkers[idx]['breite'] = 43.3449053146323;
idx++;
So that you move to next index after all operations are complete. Using them otherwise increments the value to next index which does not exist
Or if it has to stay the same way then you can initialize that value like
idx++;
arrayMarkers[idx] = [];
arrayMarkers[idx]['breite'] = 43.3449053146323;
Related
I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript
I just want set 2 arrays which should contain for loop output.
Here's code:
var key_ls = new Array();
var value_ls = new Array();
for (var a in window.localStorage) {
key_ls[a] = a;
value_ls[a] = localStorage[a];
}
and it gives me no result. What do i wrong?
What you're looking for is key_ls.push(a), which will simply add another item to the array. Also use [] instead of new Array().
Suppose I have this setup:
var whatever = new Array();
whatever["a"] = new Array();
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = new Array();
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
And I attempt to iterate through it:
$.each(whatever, function(key, value) {
$.each(value, function(subkey, subvalue) {
//stuff with key, subkey, and subvalue here
});
});
Yet the iteration fails, commenting out the nested foreach loop will allow the page to load, so that appears to be where the problem is.
Inside the first loop, I can do something like:
alert(value["a"]);
and receive the proper value, so it seems to be a "valid" array. Where am I going wrong, since the nested loop is basically the same as the outer one?
Use objects instead of arrays.
var whatever = {};
whatever["a"] = {};
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = {};
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
http://jsfiddle.net/QwT8W/
I'm trying to add markers to a google maps by iterating through a list and retrieving some information. I'm using the prototype library. The code is the following:
var point = new Array();
var myMarkerOptions = new Array();
var marker = new Array();
recommendedList.each(function(item){
point[item.location.ID] = new google.maps.LatLng(item.location.lat, item.location.lng);
myMarkerOptions[item.location.ID] = {
position: point[item.location.ID],
map: map
};
marker[item.location.ID] = new google.maps.Marker(myMarkerOption[item.location.ID]);
});
where the recommendedList is a JSON response of the form:
[
{"artist":"artist1","location":{"lat":"50.952226","lng":"5.34832","ID":28}},
{"artist":"artist2","location":{"lat":"52.362287","lng":"4.883965","ID":32}},
...
]
However, this is not working.
I know that the problem is not about the JSON or the google map, because I tried a simpler version with the following code and it worked:
var myLatlng = new google.maps.LatLng(recommendedList[0].location.lat,recommendedList[0].location.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
So the problem must be in the iteration and the hash maps.
Anyone can see the problem? Thanks!
Simple enough to test without the .each
for (var i=0, item; item = recommendedList[i]; i++) {
point[item.location.ID] = new google.maps.LatLng(item.location.lat, item.location.lng);
myMarkerOptions[item.location.ID] = {
position: point[item.location.ID],
map: map
};
marker[item.location.ID] = new google.maps.Marker(myMarkerOption[item.location.ID]);
}
You can also simplify this quite a lot, unless you "need" those other arrays:
for (var i=0, item; item = recommendedList[i]; i++) {
marker[item.location.ID] = new google.maps.Marker({
new google.maps.LatLng(item.location.lat, item.location.lng),
map
});
}
I think it could be the array accessors you're using. What are you doing the point, myMarkerOptions and marker arrays once you're done with them?
Can you try declaring them as
var point = {};
var myMarkerOptions = {};
var marker = {};
That'll let you refer to them as point[item.location.ID] (etc). I think with the item.ID property being a number, JS is trying to set that numeric index of the array, rather than creating a new property in your hash.
Prototype each iterator doesn't support JSON or object data type.
hello can anyone help me debug little error that my eyes seem to be skipping. error is: unexpected ( error. Are my array syntex correct?
function SourceClusting()
{
// grabbing count
var table = document.getElementById('OSDataCount');
var counter= table.rows[1].children[0].innerHTML
// putting all variable into arrays
var latitude()
var longitude()
var i
var marker =[];
// placing values into arrays
for (i=1;i == counter;i++)
{
longitude[i]=table.rows[i].children[6].innerHTML;
latitude[i]=table.rows[i].children[5].innerHTML;
marker[i]=new GMarker(new GLatLng(longitude[i],latitude[i]));
}
var markerCluster = new MarkerClusterer(map, marker);
}
cheers
The problems are in these lines:
var latitude()
var longitude()
You mean
var latitude;
var longitude;
or possibly
var latitude = [];
var longitude = [];
since you seem to be treating them as arrays.
Quite a few things:
You have to parseInt() the string you get from var counter = ..., as a string can't be used in comparisons with integers the way you'd like.
var latitude = () should be var latitude = [], as it's an array, Don't forget those semicolons!
You usually use a lesser-than sign in a loop, not an equality sign ==.
You can condense the loop by initializing i within it.
Try this new, possibly working code:
function SourceClusting() {
// grabbing count
var table = document.getElementById('OSDataCount');
var counter= parseInt(table.rows[1].children[0].innerHTML, 10);
// putting all variable into arrays
var latitude = [];
var longitude = [];
var marker =[];
// placing values into arrays
for (var i = 0; i < counter; i++)
{
longitude[i]=table.rows[i].children[6].innerHTML;
latitude[i]=table.rows[i].children[5].innerHTML;
marker[i]=new GMarker(new GLatLng(longitude[i],latitude[i]));
}
var markerCluster = new MarkerClusterer(map, marker);
}
var latitude() is nonsense. I suspect you mean var latitude = [];
(With a similar correction for the following line)
If you're trying to instantiate an array, instead of:
var latitude();
it should be:
var latitude = [];
You declare var latitidue(), but that doesn't make anysense. Hence the unexpected '('. Also, missing semi-colon after statement.