if statement inside for loop in javascript - javascript

I'm trying to learn javascript and getting hung up on this. Basically trying to run the loop and only select the values if profile[i] equals another variable named pro.
Here is the code that selects everything.
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var pro="<?php echo $inform['profile']; ?>";
for (var i = 0; i < markers.length; i++) {
var profile = markers[i].getAttribute("profile");
var date = markers[i].getAttribute("date");
var catch1 = markers[i].getAttribute("catch1");
var catch2 = markers[i].getAttribute("catch2");
var catch3 = markers[i].getAttribute("catch3");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("latit")),
parseFloat(markers[i].getAttribute("longit")));
var html = "<b>" + date + "</b> <br/>" + catch1 + "<br/>" + catch2 + "<br/>" + catch3;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
I tried adding
if (profile['i'] = pro)
{
after
var profile = markers[i].getAttribute("profile");
but it still loops through the whole thing.
Any suggestions?

You are assigning instead of comparing. Use == instead.
var profile = markers[i].getAttribute("profile");
if (profile['i'] == pro)
{
var date = markers[i].getAttribute("date");
var catch1 = markers[i].getAttribute("catch1");
}

Related

getElementsByTagName.textContent returns undefined

I have a XML file
<lle:Event>
<lle:eventid>ID01</lle:eventid>
<lle:collab>
<lle:name>Jane Doe</lle:name>
<lle:support>Carer</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:location>
<lle:lat>1.3117216424564617</lle:lat>
<lle:lng>103.8149642944336</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
<lle:Event>
<lle:eventid>ID02</lle:eventid>
<lle:collab>
<lle:name>Peter Smith</lle:name>
<lle:support>Carer</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:location>
<lle:lat>1.3772782313341114</lle:lat>
<lle:lng>103.89873504638672</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
<lle:Event>
...
</lle:Event>
<lle:Event>
<lle:eventid>ID08</lle:eventid>
<lle:collab>
<lle:name>Ang</lle:name>
<lle:support>Doctor</lle:support>
<lle:supportTime>8am - 8pm</lle:supportTime>
<lle:img>avatar.png</lle:img>
<lle:location>
<lle:lat>1.3577459437939223</lle:lat>
<lle:lng>103.84522878271483</lle:lng>
</lle:location>
</lle:collab>
</lle:Event>
Some lle:Event has lle:img element while some don't.
I am trying to differentiate them using javascript in order to use a custom image marker on Google map for those with lle:img element.
var events = xml.documentElement.getElementsByTagName("lle:Event");
console.log(events);
for (var i = 0; i < events.length; i++) {
var name = xml.documentElement.getElementsByTagName("lle:name")[i].textContent;
var support = xml.documentElement.getElementsByTagName("lle:support")[i].textContent;
var supportTime = xml.documentElement.getElementsByTagName("lle:supportTime")[i].textContent;
var lat = xml.documentElement.getElementsByTagName("lle:lat")[i].textContent;
var lng = xml.documentElement.getElementsByTagName("lle:lng")[i].textContent;
latLng = new google.maps.LatLng(lat, lng);
if (events[i].getElementsByTagName("lle:img").length > 0 ) {
var imgPath = xml.documentElement.getElementsByTagName("lle:img")[i].textContent;
console.log(imgPath);
var marker = new google.maps.Marker({
position: latLng,
map,
title: "Name: " + name + "\nSupport: " + support + "\nSupport Time: " + supportTime,
});
} else if (!events[i].getElementsByTagName("lle:img").length > 0) {
var marker = new google.maps.Marker({
position: latLng,
map,
title: "Name: " + name + "\nSupport: " + support + "\nSupport Time: " + supportTime,
});
}
In the above, I check for whether lle:img exist using
events[i].getElementsByTagName("lle:img").length > 0
However when i try to get imgPath with getElementsByTagName("lle:img")[i].textContent with
var imgPath = xml.documentElement.getElementsByTagName("lle:img")[i].textContent;
the console.log results always shows undefined.
Im very sure the the lle:img element is there but somehow it is still returning undefined. Is there anything wrong that im doing here?
This is what you check in your if
events[i].getElementsByTagName("lle:img").length
and this is what you use to set imgPath
xml.documentElement.getElementsByTagName("lle:img")[i].textContent
see the difference?
In particular, i is the index to the event. It makes no sense to use it to index the "lle:img" elements. You presumably have fewer "lle:img" elements than events, so your index is out of range.
Your else condition is also buggy. It probably works because !...length will be true when length is 0, and true > 0, but that's just lucky. You don't need it at all.
try this
if (events[i].getElementsByTagName("lle:img").length > 0 ) {
var imgPath = events[i].getElementsByTagName("lle:img")[0].textContent;
console.log(imgPath);
...
} else {
...
}
better yet, reduce the number of times you parse it and save your found elements:
var images = events[i].getElementsByTagName("lle:img")
if (images.length > 0) {
var imgPath = images[0].textContent
...
}
else {
...
}

Loop overring variable each time

I'm looping through to get a load of long/lats from google directions. However, longArr and latArr only ever have one result in at the end, it's as if the var is getting cleared out each time
function showSteps(directionResult) {
// For each step, place a marker, and add the text to the marker's
// info window. Also attach the marker to an array so we
// can keep track of it and remove it when calculating new
// routes.
var myRoute = directionResult.routes[0].legs[0];
var longArr = "";
var latArr = "";
for (var i = 0; i < myRoute.steps.length; i++) {
var Long = myRoute.steps[i].lat_lngs[0].B;
var Lat = myRoute.steps[i].lat_lngs[0].k;
longArr = Long + Long + "|";
latArr = Lat + Lat + "|";
alert(longArr);
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_location,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
$('.long').val(longArr);
$('.lat').val(latArr);
}
First you need to declare your arrays as arrays.
var longArr = [];
var latArr = [];
Then you need to append to them
longArr.push(Long + Long);
latArr.push(Lat + Lat);
When writing the array out to string use join
$('.long').val(longArr.join('|'));
$('.lat').val(latArr.join('|');
To concatenate with the existing value of the string you have to concatenate the variable too.
Option 1:
longArr = longArr + Long + Long + "|" ;
latArr = latArr + Lat + Lat + "|";
Option 2:
longArr += Long + Long + "|" ;
latArr += Lat + Lat + "|";

repeat xml data into a div

I have a function which retrieve data from a xml file and then it is supposed to show it in a div. The problem is that I only get the last element of the array. Is there a way to obtain all the elements and populate them into the div?
Here is the function:
function paradascamionesHistorico() {
google.maps.event.addListener(map, 'click', function() {
infowindowMarkerParadas.close();
});
var Boton = document.getElementById('Boton').value;
var textboxImei = document.getElementById('imeiHistorico').value;
var textboxFecha = document.getElementById('fechaInicioHistorico').value;
var textboxFechaFin = document.getElementById('fechaFinHistorico').value;
var textboxDesdeHora = document.getElementById('desdeHoraHistorico').value;
var textboxHastaHora = document.getElementById('hastaHoraHistorico').value;
downloadUrl("paradas.asp?imei="+textboxImei+"&fecha="+textboxFecha+" "+textboxDesdeHora+"&fechaFin="+textboxFechaFin+" "+textboxHastaHora,
function(data) {
var xml = xmlParse(data);
var markersParadas = xml.documentElement.getElementsByTagName("marker");
var position = [];
//var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markersParadas.length; i++) {
var lat = parseFloat(markersParadas[i].getAttribute("lat"));
var lng = parseFloat(markersParadas[i].getAttribute("lng"));
var myLatlngParadas = new google.maps.LatLng(lat, lng);
var fechaInicio = markersParadas[i].getAttribute("fechaInicio");
var fechaFinal = markersParadas[i].getAttribute("fechaFinal");
var diferencia = markersParadas[i].getAttribute("diferencia");
//alert(+diferencia);
var datearray = diferencia.split("/");
var newDate = datearray[1] + '/' + datearray[0] + '/' + datearray[2];
var aFecha = new Date(newDate);
var hours = aFecha.getHours();
var minutes = aFecha.getMinutes();
var seconds = aFecha.getSeconds();
var markerParadas = createMarkerParadas(myLatlngParadas, hours, minutes, seconds, fechaInicio, fechaFinal);
myMarkersParadas.push(markerParadas);
var tablaParadas = '<a href="javascript:myclickParadas(' + (myMarkersParadas.length-1) + ')">' + seconds + '<\/a><br>';
document.getElementById("paradasDiv").innerHTML = tablaParadas;
}//finish loop
}); //end download url
}//termina function
function myclickParadas(i) {
google.maps.event.trigger(myMarkersParadas[i], "click");
}
So if anyone knows how to show the rest of the elements of the array I will be very gratefully.
Best regards.
document.getElementById("paradasDiv").innerHTML = tablaParadas;
You are overwriting innerHTML of #paradasDiv on each iteration of your loop.
That's why you only see the last element of the array.
You have to append to it:
document.getElementById("paradasDiv").innerHTML += tablaParadas;
Also, before starting the loop you maybe need to empty it:
document.getElementById("paradasDiv").innerHTML = '';

Javascript function works on postback but not page load

I'm using a Google Maps plugin, and I want it to show up on the page load as well as all postbacks. It seems to only work on postbacks though. Any ideas? I have the body onload tag as "body background="#ccccff" onload="initialize()"", but the function is not defined the first time. Why? Here is the code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
var mostRecentInfo;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
center: center,
zoom:1,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var posStr = <%=JSON%>;
if (posStr.toString() != "0") {
var test = posStr.toString().split(',');
var groundstation = <%=groundStation%>;
var dateTimeStr = <%=datetimesStr%>;
var AUStr = <%=auStr%>;
var spaceCraft = <%=spacecraft%>;
var dateTimes = dateTimeStr.toString().split(',');
var auIDs = AUStr.toString().split(',');
var latitude = new Array((test.length / 2));
var longitude = new Array(latitude.length);
var i = 0;
var markerArray = new Array();
for (var j = 0; j < (test.length - 1); j = j + 2) {
latitude[i] = eval(test[j+1]);
longitude[i] = eval(test[j]);
var position = new google.maps.LatLng(latitude[i], longitude[i]);
var marker = new google.maps.Marker({
map:map,
position:position
});
markerArray.push(marker);
i++;
}
var sumLat = 0;
var sumLong = 0;
for (i = 0; i < latitude.length; i++) {
sumLat += latitude[i];
sumLong += longitude[i];
}
var avgLat = sumLat / latitude.length;
var avgLong = sumLong / longitude.length;
center = new google.maps.LatLng(avgLat, avgLong);
map.panTo(center);
var circle;
var contentStr = new Array();
for (i = 0; i < markerArray.length; i++) {
position = markerArray[i].getPosition();
var circOptions = {
strokeColor:"#770000",
strokeOpacity:0.1,
fillColor:"#881111",
fillOpacity:0.4,
map:map,
center:position,
radius:2500000
};
circle = new google.maps.Circle(circOptions);
marker = markerArray[i];
contentStr[i] = '<div id="content">' +
'<b>Spacecraft: </b>' + spaceCraft.toString() + '<br />' +
'<b>Start Time (UTC): </b>' + dateTimes[i].toString() + '<br />' +
'<b>Position: </b>(' + latitude[i].toString() + ', ' + longitude[i].toString() + ')<br />' +
'<b>AU ID: </b>' + auIDs[i] + '<br />' +
'<b>Downlink Station: </b>' + groundstation.toString() + '<br />' +
'</div>';
addListener(map, marker, contentStr[i]);
}
}
}
function addListener(map, marker, content) {
var infowindow = new google.maps.InfoWindow({
content:content
});
google.maps.event.addListener(marker, 'mouseover', function() {
if (mostRecentInfo)
mostRecentInfo.close();
mostRecentInfo = infowindow;
infowindow.open(map, this);
});
}
etc.
It is likely a timing issue with the onload function being called before the initialize function is ready. This is the reason libraries like jQuery have a document.ready function. You can try removing the onload and place a call to initialize() at the bottom of your HTML, just prior to the closing body tag. This will probably work for you.
If you have the option, I'd use a library so you can assure that the function is there and your page is ready. If you haven't tried it, give jQuery a shot.

Javascript insists it's not defined, it totally is

I'm not used to writing JS, honestly, and to make matters worse I'm working with the Google Maps API which, while well-documented, is a bear. So, I've written a function that allows a users to zoom onto the map from a link. But the interpreter insists my function isn't defined when I call it. The function is "zoomTo" and it appears in the following monster script.
function load() {
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var i = 0;
// Read the data
//++++++++++++++++
GDownloadUrl("/assets/data/nolag.xml", function(data) {
var xml = GXml.parse(data);
var markers =
xml.documentElement.getElementsByTagName("marker");
// Draw icons
for (var i = 0; i < markers.length; i++) {
var locoName = markers[i].getAttribute("locoName");
var speed = markers[i].getAttribute("speed");
var ip = markers[i].getAttribute("ip");
var date = markers[i].getAttribute("captureTime");
var lat = markers[i].getAttribute("lat");
var lng = markers[i].getAttribute("lng");
var location = markers[i].getAttribute("location");
var heading = markers[i].getAttribute("heading");
var type = markers[i].getAttribute("type");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, locoName, speed, ip, date, lat, lng, location, heading, type);
map.addOverlay(marker);
}
});
// create the map
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40.5500, -72.1700), 7);
map.enableScrollWheelZoom();
NEC = new GPolyline(NECRoute, "#0d004c", 3, 0.7);
map.addOverlay(NEC);
// A function to create the marker and set up the event window
//+++++++++++++++++
function createMarker(point, locoName, speed, ip, date, lat, lng, location, heading, type) {
var marker = new GMarker(point, customIcons[type]);
marker.tooltip = '<div class="tooltip"><h1>' + locoName + '</h1><h2>' + speed + '<br/>' + location + '</h2></div>';
marker.contextmenu = '<div class="contextmenu">Hello world</div>';
var satellite = "<img src=\"./images/icons/satellite.gif\">";
var gps = "<img src=\"./images/icons/gps.gif\">";
var cmu = "<img src=\"./images/icons/cmu.gif\">";
var ftp = "<img src=\"./images/icons/ftp.gif\">";
var me1k = "<img src=\"./images/icons/me1k.gif\">";
var html = "<div class=\"bubble\">";
html += "<h3>" + locoName + "<span class=\"small-data\"> Route 2150</span></h3>";;
html += "<div class=\"toolbar\">" + gps + satellite + cmu + ftp + me1k + "</div>";
html += "<h4>Heading " + heading + " # " + speed + " MPH</h4>"
html += "<h4>Lat: " + lat + "</h4><h4> Lng: " + lng + "</h4>";
html += "<h4>IP: " + ip + "</h4>";
html += "<h4><div class=\"sm-button\"><a style='color: #FFFFFF; decoration:none;' href='map_detail.php'>Details</a></div><div class=\"sm-button\">Zoom To</div></h4>";
html += "</div>";
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
// ====== The new marker "mouseover" and "mouseout" listeners ======
GEvent.addListener(marker,"mouseover", function() {
showTooltip(marker);
});
GEvent.addListener(marker,"mouseout", function() {
tooltip.style.visibility="hidden"
});
return marker;
}
// ====== This function displays the tooltip ======
//+++++++++++++++++++++++++++++++++++++++++++++++++++
function showTooltip(marker) {
tooltip.innerHTML = marker.tooltip;
var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
var anchor=marker.getIcon().iconAnchor;
var width=marker.getIcon().iconSize.width;
var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
pos.apply(tooltip);
tooltip.style.visibility="visible";
}
// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
function mymouseover(i) {
showTooltip(gmarkers[i])
}
// ===== This function is invoked when the mouse leaves an entry in the side_bar =====
function mymouseout() {
tooltip.style.visibility="hidden";
}
// This function picks up the side_bar click and opens the corresponding info window
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
// ====== set up marker mouseover tooltip div ======
var tooltip = document.createElement("div");
document.getElementById("map").appendChild(tooltip);
tooltip.style.visibility="hidden";
// === create the context menu div ===
var contextmenu = document.createElement("div");
contextmenu.style.visibility="hidden";
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
contextmenu.innerHTML = '<div class="context"><ul>'
+ '<li class="sectionheading">Zoom Out</li>'
+ '<li class="sectionheading">Boston Area</li>'
+ '<li>South Station, Boston</li>'
+ '<li>South Hampton</li>'
+ '<li>New Haven</li>'
+ '<li class="sectionheading">New York Area</li>'
+ '<li>Sunny Side</li>'
+ '<li>NY, Penn Station</li>'
+ '<li>30th Street, Philadelphia</li>'
+ '<li>Wilmington Shops</li>'
+ '<li>Baltimore, Penn Station</li>'
+ '<li class="sectionheading">DC Area</li>'
+ '<li>DC, Ivy City</li>'
+ '<li>DC, Union Station</li>'
+ '</ul</div>';
map.getContainer().appendChild(contextmenu);
// === listen for singlerightclick ===
GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
clickedPixel = pixel;
var x=pixel.x;
var y=pixel.y;
if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
pos.apply(contextmenu);
contextmenu.style.visibility = "visible";
});
// === If the user clicks on the map, close the context menu ===
GEvent.addListener(map, "click", function() {
contextmenu.style.visibility="hidden";
});
} else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
}
It appears that zoomTo is an annonymous function inside of the top-level function load() - therefore, it's not available to top-level calls.
Instead of
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
put the function in the top level, and pass in the map and contextmenu variables:
// === functions that perform the context menu options ===
function zoomTo( lat, lng, level) {
// perform the requested operation
map.setCenter( new GLatLng(lat,lng), level);
// hide the context menu now that it has been used
contextmenu.style.visibility="hidden";
}
As it dont looks well in comment. posting the comment above here again
<html>
<head>
<script type="text/javascript">
function zoomTo(x,y,z) {
....
}
</script>
.....
</head>
......
</html>

Categories

Resources