I have json data, and the data is displayed in a pop up on a map
when there is a data that does not exist (Visibility), then the word undefined appears on the pop up
How to remove undefined text, so that it gets deleted on the pop up?
json data :
[{
"date":"03-03-2022",
"lat":-5.67,
"lng":80.65,
"weather":"2",
"temperature": "24.4",
"Humidity": "90",
"Wind": "100"}]
script js :
<script>
for (i = 0; i < dataJSON.length; i++) {
var weather = parseInt(dataJSON[i].weather)
var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
var marker = L.marker(Coordinate, { icon: customIcon })
marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
+ 'wind :' + dataJSON[i].Wind + 'Visibility :' + dataJSON[i].Vis
)
}
Pop Up :
Help me, Please . . .
You are getting the 'undefined' in Visibility since the property 'Vis' is not a part of json data.
You can use the following code in script.js to remove undefined from the popup and replace it with blank:
<script>
for (i = 0; i < dataJSON.length; i++) {
var weather = parseInt(dataJSON[i].weather)
var Coordinate = new L.latLng(([dataJSON[i].lat, dataJSON[i].lng]))
var marker = L.marker(Coordinate, { icon: customIcon })
marker.bindPopup('Date : ' + dataJSON[i].date + 'Temperature : ' + dataJSON[i].temperature + 'RH :' + dataJSON[i].Humidity
+ 'wind :' + dataJSON[i].Wind + (dataJSON[i].Vis == undefined?'':'Visibility :' + dataJSON[i].Vis)
)
}
</script>
Related
I am adding Json data to html div and parsing.it is working fine in local.but it is throwing error when we are running file from server .the error is "unexpected token o".
var data = $.parseJSON($("#json-data").html());
//console.log(data);
var now = new Date();
var events = [];
if (data != undefined && data.results.assets.length > 0) {
var dayevents = [];
$.each(data.results.assets, function(i, entry) {
var d = entry.metadata.EventDate;
$('#calender-list').append('<div class="events-list-main"><div class="events-list"><div class="event-title">' + entry.metadata.EventName + '</div><div class="event-addr">' + (entry.metadata.EventDate) + '-' + (entry.metadata.EventEndDate). + ' ' + (entry.metadata.EventEndDate). + '<br/>' + entry.metadata.EventAddress + '</div><div class="event-desc">' + entry.metadata.EventDesc + '</div>SEE EVENT WEBSITE<em class="icon-go"></em></div></div>');
});
}
fiddle
There are .+ at (entry.metadata.EventEndDate). +.
They should be something like (entry.metadata.EventEndDate) + '<br/>'
fiddle
I'm working through a project to show information from a third party api on a map.
I'm not very experienced figuring out what the console is telling me so I'm a little stuck on the error I'm getting. I've declared all the variables outside of the function so result is defined and all of these functions are aspects of a foursquare venue.
Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
result = data.response.venue;
contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
Not sure what data the call you are making is supposed to return but the error you are getting indicates that you did not get the data you were expecting.
result = data.response.venue;
"venue" is not a defined property of data.response so when you try and access result.hasOwnProperty('contact') it has no idea what to return since result is not defined.
I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Ok, I am new to JQuery and I have requirement to do some manipulation on table based on rows.
The table consists of rows which belong to 3 different style classes Brand have category and category have products.
var table = $("table tbody");
table.find(".brand").each(function(i) {
var $tdsBrand = $(this).find("td"),
brand = $tdsBrand.eq(0).text(),
atyBrand = $tdsBrand.eq(1).text(),
alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (i + 1) + ':\nBrand Name: ' + brand + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var brandClass = $(this).attr("class");
console.log('brand class : ' + brandClass);
if (this row has next row as category) {
//if(brand.next($( "tr[class='category']" ))) {
//if ("(.band):has(.category)") {
//if ($(this).parents(".category").length == 1) {
table.find(".category").each(function(i) {
var catClass = $(this).attr("class");
console.log('category class : ' + catClass);
var $tdsCategory = $(this).find("td"),
category = $tdsCategory.eq(0).text(),
atyCategory = $tdsCategory.eq(1).text(),
alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row ' + (i + 1) + ':\nCategory Name: ' + category + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
if (This row has next row as product) {
//if(next($( "tr[class='product']" ))) {
//if ("(.category):has(.product)") {
//if ($(this).parents("product").length == 1) {
table.find(".product").each(function(i) {
var proClass = $(this).attr("class");
console.log('product class : ' + proClass);
var $tds = $(this).find("td"),
product = $tds.eq(0).text(),
aty = $tds.eq(1).text(),
aly = $tds.eq(2).text();
console.log('Product Row ' + (i + 1) + ':\nProduct Name: ' + product + '\nActual TY: ' + aty + '\nActual LY: ' + aly);
});
}
});
}
});
What I want to do is, I have to sum up Actual TY values of products and display them on their category. Then sum up Actual TY of categories (which has been calculated from products for different categories) to their brand.
Please refer http://jsfiddle.net/cfhhz0zr/46/ for clear understanding of my requirement and code which I've tried till now.
Thank you.
Just modified a bit your code and it seems that is doing what you are looking for. See also the http://jsfiddle.net/88prg1dt/
I refactored a bit and renamed some variables to make a bit more sense so should be fairly clear now. If you want to calculate the total for a product / category now should be really super simple.
Here is the JS code:
var $table = $("table tbody");
$table.find(".brand").each(function (brandIndex) {
var $brandRow = $(this);
var $tdsBrand = $(this).find("td");
var brandName = $tdsBrand.eq(0).text();
var atyBrand = $tdsBrand.eq(1).text();
var alyBrand = $tdsBrand.eq(2).text();
console.log('Brand Row ' + (brandIndex + 1) + ':\nBrand Name: ' + brandName + '\nActual TY: ' + atyBrand + '\nActual LY: ' + alyBrand);
var $categoryRows = $brandRow.nextUntil('.brand').filter('.category');
$categoryRows.each(function (categoryIndex) {
var $categoryRow = $(this);
var $tdsCategory = $categoryRow.find("td");
var categoryName = $tdsCategory.eq(0).text();
var atyCategory = $tdsCategory.eq(1).text();
var alyCategory = $tdsCategory.eq(2).text();
console.log('Category Row: ' + (categoryIndex + 1) + ':\nCategory Name: ' + categoryName + '\nActual TY: ' + atyCategory + '\nActual LY: ' + alyCategory);
var $productRows = $categoryRow.nextUntil('.brand, .category').filter('.product');
$productRows.each(function (productIndex) {
var $productRow = $(this);
var $tdProducts = $productRow.find("td");
var productName = $tdProducts.eq(0).text();
var atyProduct = $tdProducts.eq(1).text();
var aly = $tdProducts.eq(2).text();
console.log('Product Row ' + (productIndex + 1) + ':\nProduct Name: ' + productName + '\nActual TY: ' + atyProduct + '\nActual LY: ' + aly);
});
});
});
I played a bit with jQuery nextUntil() method as the documentation:
Description: Get all following siblings of each element up to but not
including the element matched by the selector, DOM node, or jQuery
object passed.
Is this answering your question ?
I am using Facebooks Javascript API to import to my website the albums and photos of a Facebook page.
My javascript code looks like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '5698434687426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('1607099163/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
}
});
})(i);
} //end of for loop
}
});
};
As you can see in the beginning i use the API to get information about the albums of the specific page : FB.api('169070991963/albums', function(response) {...}
Everything works as expected and i can get information as albumNames , albumCovers , albumIds etc .
Now for every album that i import , i want to have an array where i will save all of its pictures and thumbnails. For this reason i make another API call , FB.api(albumId + "/photos", function(response) {} .
I process the response like this :
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
At this point though i get the error : Uncaught TypeError: Cannot set property '0' of undefined
I cant understand what is undefined though... Any idea on this ?
*By the way the next API call that i make FB.api( albumCover, function(response) {..} to get the cover photos of the albums and create a jquery mobile listView , works too.
EDIT
The answer provided below solved the 2-dimensional table problem.
However now the error is : Uncaught TypeError: Cannot read property 'picture' of undefined
EDIT2
I am experiencing the same issue later in the code so i am making this EDIT. The code now looks as suggested like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '564984346887426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('169070991963/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count;
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
}
});
})(i);
} //end of for loop
console.log(albumPhotos);
console.log(albumThumbnails);
}
});
};
I added this piece of code as you see :
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
Every row in the 2dimensional table albumPhotos is an album and every column is a photo inside this album. With the for loop above i tried to create a list of Galleries that every Gallery has an album with all its photos.
Again i get the error :
Uncaught TypeError: Cannot read property '0' of undefined
Uncaught TypeError: Cannot read property '1' of undefined
Uncaught TypeError: Cannot read property '2' of undefined
Uncaught TypeError: Cannot read property '3' of undefined
.
.
.
Why do i get this now?
You have albumThumbnails and albumPhotos as empty arrays, and in the loop you are trying to add values into the array.
let us take the case where i = 0 your array albumThumbnails has a length of 0 that means albumThumbnails[0] is undefined, then you are trying to set albumThumbnails[0][0] which is giving the error.
The solution here is to first create an empty object at the index i if required then set its property
Looks like you are trying to create the object here
for(var k=0; k<numberOfPhotos && k < response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}