Populating 2D Array in JS - javascript

I am trying to popoulate a 2D array using Firebug API,
var sites = [];
var siteCounter = 0;
//Firebase API Calls
var messageListRef = new Firebase('https://my.firebaseio.com');
messageListRef.once('value', function(allMessagesSnapshot) {
allMessagesSnapshot.forEach(function(messageSnapshot) {
var latitude = messageSnapshot.child('latitude').val();
var longitude = messageSnapshot.child('longitude').val();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
siteCounter++;
alert(sites[siteCounter][1] + " " + sites[siteCounter][2] );
});
});
But this breaks for sites[siteCounter][0] and says it is undefined. Any clue how to work with this ?

if you want 2D array, you must to initialize like this :
var tab = new Array();
after
tab[0] = new Array();
Try this code
sites[siteCounter] = new Array();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
or directly
sites[siteCounter] = new Array("siteCounter", latitude, longitude, siteCounter, "This is siteCounter.");

Have you tried to do a
sites[siteCounter] = [];
before sites[siteCounter][0]?
I assume you have to declare it as an array to be able to put stuff in the array.

Related

looped values are not printing in div via javascript

I am trying to print the address and details of my clinics in various locations. However, when i try to do that it is only printing the first element in my div.
Here is my code
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var locname = markerNodes[i].getAttribute("locationName");
var locaddress = markerNodes[i].getAttribute("locationAddress1");
var address = markerNodes[i].getAttribute("locationAddress1");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var servicename = markerNodes[i].getAttribute("serviceName");
var clinicfname= markerNodes[i].getAttribute("clinicFname");
var cliniclname= markerNodes[i].getAttribute("clinicLname");
var clinicname= clinicfname + ' ' + cliniclname ;
var clinicAddress= markerNodes[i].getAttribute("clinicAddress");
var clinicCity= markerNodes[i].getAttribute("clinicCity");
var clinicPhone= markerNodes[i].getAttribute("clinicPhone");
var cname= markerNodes[i].getAttribute("cname");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("locationLat")),
parseFloat(markerNodes[i].getAttribute("locationLong")));
document.getElementById('details_name').innerHTML = clinicname;
//console.log (parseFloat(markerNodes[i].getAttribute("locationLong")));
createdetails(clinicname,clinicAddress)
bounds.extend(latlng);
}
In above code am calling a function name createdetails
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML=clinicname;
document.getElementById("details_address").innerHTML=clinicAddress;
}
But this div is priniting only first name and first addrees.It have 9 diffrent values for name and address.When i consoled it,it prints.
What is the problem here?
When you are calling document.getElementById("details_name").innerHTML = ..., you are overwriting the current value. Maybe you should append the new name to the existing content with +=:
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML+=clinicname;
document.getElementById("details_address").innerHTML+=clinicAddress;
}

How to get all the pins/markers in on click of a markercluster in google maps?

I am using google maps api to create a store locator with clusters and I am referring the marker cluster api.
I wanted to get the list of stores with in a markercluster rather than returning marker cluster with pins/markers. Please find the below code -
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = "";
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
$(mapsCore.mapsVar.totalResults.Result).each(function(k, v) {
$(markers).each(function(km, vm) {
if (parseFloat(v.LAT) == parseFloat(markers[km].position.lat()) && parseFloat(v.LON) == parseFloat(markers[km].position.lng())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.Counter_ID = v.Counter_ID;
x.Counter_Name = v.Counter_Name;
x.Counter_Zip_code = v.Counter_Zip_code;
x.Address_1 = v.Address_1;
x.Address_2 = v.Address_2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.Counter_Tel = v.Counter_Tel;
x.Counter_Email = v.Counter_Email;
x.Open_Time = v.Open_Time;
x.Close_Time = v.Close_Time;
x.LAT = v.LAT;
x.LON = v.LON;
x.MR_FLG = v.MR_FLG;
mapsCore.mapsVar.clusterDetail.Results.push(x);
x = {};
}
});
});
});
As a workaround you can set a custom image to an transparent png and text size to 0, that way it'll be invisible on the map.
cluster.setStyles({
url: your_path/transparent.png,
height: 20,
width: 20,
textSize: 0
});
Alternatively you can try and see if setting the image height and width to 0 works.
All,
thanks for your help for formatting my code and comments any way I found the solution for it. I will attach the spinet of code below
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
$(mapsCore.mapsVar.totalResults.Counters).each(function(k, v) {
$(markers).each(function(km, vm) {
console.log(parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat()) && parseFloat(v.CounterLongitude) == parseFloat(vm.position.lng()));
if (parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.CounterCode = v.CounterCode;
x.CounterName = v.CounterName;
x.CounterZipCode = v.CounterZipCode;
x.AddressLine1 = v.AddressLine1;
x.AddressLine2 = v.AddressLine2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.CounterPhoneNumber = v.CounterPhoneNumber;
x.CounterEmailAddress = v.CounterEmailAddress;
x.CounterOpenTime = v.CounterOpenTime;
x.CounterCloseTime = v.CounterCloseTime;
x.CounterLatitude = v.CounterLatitude;
x.CounterLongitude = v.CounterLongitude;
x.IsMagicRingAvailable = v.IsMagicRingAvailable;
mapsCore.mapsVar.clusterDetail.Counters.push(x);
x = {};
}
});
});
console.log(mapsCore.mapsVar.clusterDetail);
var template = $.templates("#mapslist");
var output = template.render(mapsCore.mapsVar.clusterDetail);
$(".store-list-section").html(output);
});
Always need to reset the array of object like -
mapsCore.mapsVar.clusterDetail.Counters.length = 0;

Adding destination lat and lon to destinations variable distancematricx API Success and Fail

I'm trying to get the lat and lon from a Json encoded file for use as destinations for the distance Matrix API rather than add var destinationA = new google.maps.LatLng(??.????, ???.?????); multiple times.
I thought I managed it, as both ways seem to produce the same variable destinations when viewed, yet method two produces an error Uncaught TypeError: a.lat is not a function
This is method one which gives var destination a length of 7:
var destinationA = new google.maps.LatLng(13.7373393, 100.5558883);
var destinationB = new google.maps.LatLng(13.735132, 100.55611199999998);
var destinationC = new google.maps.LatLng(13.736953, 100.55819300000007);
var destinationD = new google.maps.LatLng(13.736244, 100.55694100000005);
var destinationE = new google.maps.LatLng(13.736166, 100.557203);
var destinationF = new google.maps.LatLng(13.738747, 100.55587700000001);
var destinationG = new google.maps.LatLng(13.733558, 100.56020699999999);
var destinations = [destinationA,destinationB,destinationC,destinationD,destinationE,destinationF,destinationG];
works great, will return the distances for each from a given centre point on google map.
Method two:
This is method Two which gives var destination a length of 1, which I am stuck on finding out why its a single length and not 7 as above:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
var first = true;
for (var i=0; i < location_lat_lon.length; i++) {
var sep = first ? '' : ',';
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(lat, lon);
var destinations = [destinations+sep+destination1] ;
first = false;
}
which returns exactly the same result when viewing the variable destinations, yet this returns the error Uncaught TypeError: a.lat is not a function.
Any advice or guidance?
Is it not possible to pass destinations this way to the calculateDistances function?
Thanks in Advance :)
Try this:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
for (var i=0; i < location_lat_lon.length; i++) {
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
destinations.push(destination1);
}

Having trouble with image preload code

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.
1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

JavaScript, advanced .replace()

function changeText(getString){
var smiles_from_to = new Array();
smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
var replaced = getString;
for(var key in smiles_from_to){
replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
}
return replaced;
}
Hi everyone ,I need to optimize code for something more simple, so try to avoid for loop..
"var replaced" is a huge html code (content of div that contains 100 lines of messages with date, username, userinfo(tooltip), message,.....)
This code is a piece from my chrome extension. so i cant do it php side.
You can use a single giant regex, of the form /:\)|:\(|.../g, then pass a callbacka as the replacement that looks up the match in your lookup object.

Categories

Resources