Trouble passing JSON data into embedded map - javascript

I'm trying to build a page that will display several points on a map, each representing a scheduled event with a Title, location, date, link, and description. For the map itself, I'm using the maplace plugin (http://maplacejs.com), and the events are being stored in a .json file. Currently, I get no errors in the log, and the map appears on page load, but the points don't appear. Here's the relevant code:
data.json
{ "allEvents": [
{
"eventName" : "Event #1",
"eventDate" : "May 27, 2014",
"lat": "52.963619",
"long": "-125.619140",
"link": "http://www.google.com"
"description" : "short description"},
]}
in my header script
var eventLocations = [];
$.getJSON('data.json', function(events) {
for (var i in data.allEvents) {
var name = data.allEvents[i].eventName;
var date = data.allEvents[i].eventDate;
var latitude = data.allEvents[i].lat;
var longitude = data.allEvents[i].long;
var link = data.allEvents[i].link;
var desc = data.allEvents[i].description;
var loc = "{ lat: " + latitude + "," +
"lon: " + longitude + "," +
"icon: images/icon3.png," +
"title: " + name + "," +
"html: <div class='infoWindow'>" +
"<h3>" + name + "</h3>" +
"<h4>" + date + "</h4>" +
"<a href='http://" + link + "' target='_blank'>view website</a>" +
"<p>" + desc + "</p>" +
"</div> },";
eventLocations.push(loc);
};
});
and
$(function() {
var maplace = new Maplace({
//I have lots of other parameters here (controls, stylers, options, etc)
locations: [ eventLocations ]
});
maplace.Load();
It's also worth mentioning that if I write out one location in the Maplace (i.e. in place of the 'eventLocations' variable, the pin shows up fine.
Thanks in advance!

Related

How to paginate the JSON data at client side without using Bootstrap?

Solution is in this JSFiddle: https://jsfiddle.net/rinku16/mpo7xyjk/17/
When the user click on Filter Search and JSON is downloaded on client side according to the search condition and my pagination JS function partition the rows according to number of rows per page and accordingly make numeral navigation button between previous and next buttons.
I have problem of synchronization of navigation button for pages and previous/Next Button.
My Problem as follows
For example: Initially on search click it displays only table header but if user presses next button it displays (10-19) 10 records continuing (skipped) after 0-9 of previous rows but if user click 0 navigation button (between previous and next buttons) but it displays (0-1-2) 3 rows (but it should display 0-9 rows) and when click on 1 button it should display (10-19) but it displaying (3-4-5).
I have updated the code in this JSFiddle link (https://jsfiddle.net/rinku16/hn3t9gz6/33/) but it is not working properly.
I am trying to build a logic. You can check all logic at the link. I am not able to do following task.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="row">
<div class="col">
<div>
Pagination Div
<div id="pagination"></div>
</div>
</div>
</div>
<div class="row" style="overflow-x:auto;">
<div class="col">
<div>
Records Div
<div id="filterRecords"></div>
</div>
</div>
</div>
</body>
</html>
Logic for client side:
// This is script to load table based on filter section
$(document).ready(function() {
userDetails = [{
"Lead_Id": "66",
"FirstName": "John",
"LastName": "Doe",
"Company": "Google",
"Website": "www.google.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/john-doe",
"Email": "johndoe#google.com",
"Phone": "5125501553",
"State": "Delaware",
"Country": "USA",
"TechArea": "Cloud computing",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-02-03",
"NextContactDate": "2020-02-29",
"LeadDescription": "This is lead description testing",
"OwnerNotes": null,
"SetReminder": "2020-02-29",
"AdminNotes": "This is admin notes testing",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-02-03 16:28:26",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}, {
"Lead_Id": "67",
"FirstName": "Tohn",
"LastName": "Doe",
"Company": "Microsoft",
"Website": "www.microsoft.com",
"Designation": "Manager",
"Linkedin": "www.linkedin.com\/tohn-doe",
"Email": "tohn#microsoft.com",
"Phone": "123456",
"State": "California",
"Country": "USA",
"TechArea": "Computer Networks",
"FirmType": "Corporate",
"FirmSize": "Less than 10",
"LastContactDate": "2020-03-05",
"NextContactDate": "2020-03-07",
"LeadDescription": "This is test lead description",
"OwnerNotes": null,
"SetReminder": "2020-03-11",
"AdminNotes": "This is testing admin notes",
"LeadStatus": "Planned",
"LeadAddedBy": "18",
"LeadAddedOn": "2020-03-05 10:47:21",
"LeadUpdatedBy": null,
"LeadUpdatedOn": null
}];
//More JSON object you can get on jsfiddle link
$("#filterRecords").empty();
var result = $.parseJSON(userDetails);
//###########################################
// Pagination code start
//###########################################
$("#pagination").attr('style', 'display:block;');
$('#pagination').html('<div class="row"><div class="col"><button class="col PreviousButton" id="PreValue"><i class="ion-skip-backward"></i> Previous</button></div> <div id="nav-numbers" class="col nav"></div> <div class="col"><button class="col NextButton" id="nextValue">Next <i class="ion-skip-forward"></i></button></div></div>');
paginate_json_data(result)
$("#filterRecords").html(table);
//###########################################
// Pagination code end
//###########################################
});
function paginate_json_data(userDetails) {
var table = '';
table = $("<table></table>");
table.append('<thead><th>#</th><th>Name</th><th>Company</th><th>Website</th><th>Designation</th><th>Linkedin</th><th>Email</th><th>Phone</th><th>State</th><th>Country</th><th>TechArea</th><th>Firm Type</th><th>Firm Size</th><th>Last Contact Date</th><th>Next Contact Date</th><th>Lead Description</th><th>Owner Notes</th><th>Reminder Date</th><th>Admin Notes</th><th>Lead Status</th><th>Lead Added By</th><th>Lead Added On</th><th>Lead Updated By</th><th>Lead Updated On</th></thead><br>');
table.append('<tbody id="myTable"></tbody>');
userDetails = userDetails
$('#pagination').append('<p1>Total number of rows fetched: ' + userDetails.length + '</p1>');
var max_size = userDetails.length;
var sta = 0;
var elements_per_page = 10;
// var elements_per_page = rows_per_page;
var limit = elements_per_page;
goFun(sta, limit);
function goFun(sta, limit) {
// console.log(sta,limit);
for (var i = sta; i < limit; i++) {
var tab = '<tr><td>' + i + "\n" + '</td><td>' + "<a target='_blank' href=./lead/index.html?lead_id=" + userDetails[i].Lead_Id + " </a>" + userDetails[i].FirstName + ' ' + userDetails[i].LastName + "\n" + '</td><td>' + userDetails[i].Company + "\n" + '</td><td>' + userDetails[i].Website + "\n" + '</td><td>' + userDetails[i].Designation + "\n" + '</td><td>' + userDetails[i].Linkedin + "\n" + '</td><td>' + "" + userDetails[i].Email + "" + "\n" + '</td><td>' + userDetails[i].Phone + "\n" + '</td><td>' + userDetails[i].State + "\n" + '</td><td>' + userDetails[i].Country + "\n" + '</td><td>' + userDetails[i].TechArea + "\n" + '</td><td>' + userDetails[i].FirmType + "\n" + '</td><td>' + userDetails[i].FirmSize + "\n" + '</td><td>' + userDetails[i].LastContactDate + "\n" + '</td><td>' + userDetails[i].NextContactDate + "\n" + '</td><td>' + userDetails[i].LeadDescription + "\n" + '</td><td>' + userDetails[i].OwnerNotes + "\n" + '</td><td>' + userDetails[i].SetReminder + "\n" + '</td><td>' + userDetails[i].AdminNotes + "\n" + '</td><td>' + userDetails[i].LeadStatus + "\n" + '</td><td>' + "<a target='_blank' href=./account/index.html?user_id=" + userDetails[i].LeadAddedBy + " </a>" + userDetails[i].LeadAddedBy + "\n" + '</td><td>' + userDetails[i].LeadAddedOn + "\n" + '</td><td>' + userDetails[i].LeadUpdatedBy + "\n" + '</td><td>' + userDetails[i].LeadUpdatedOn + "\n" + '</td></tr>';
$('#myTable').append(tab)
}
}
$('#nextValue').click(function() {
var next = limit;
if (max_size >= next) {
def = limit + elements_per_page;
limit = def
$('#myTable').empty();
if (limit > max_size) {
def = max_size;
}
goFun(next, def);
}
});
$('#PreValue').click(function() {
var pre = limit - (2 * elements_per_page);
if (pre >= 0) {
limit = limit - elements_per_page;
$('#myTable').empty();
goFun(pre, limit);
}
});
var number = Math.round(userDetails.length / elements_per_page);
for (i = 0; i <= number; i++) {
$('.nav').append('<button class="nav-numbers btn" id=' + i + '>' + i + '</button>');
}
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 3 * (parseInt(start) + 1) > max_size ? max_size : 3 * (parseInt(start) + 1)
goFun(start * 3, limit);
});
}
I want to do two things using paginate.
Partition the number of rows example: JSON has 32 rows then rows view per page 10 then i have buttons as 1 (10 row), [2] (10 rows),[3] (10 rows), [4] (2 rows) {I have written code for this in link}
Move the focus from one button to next button on (next button click) 1 -> [2] -> [3] -> [4]) {I have not written code for this as it need CSS changes using button id(1->[2]->[3]->[4])}
The problem is button click previous and next are not synchronized with focused buttons (1->[2]->[3]->[4]).
Screenshot of my work until now.
Please correct my code.
If understand it right, if you click the button 1,2 or 3 it shows only the next 3 new but should show the next 10 new.
then change the following:
change the "3" to "10" in your code
$('.nav button').click(function() {
var start = $(this).text();
$('#myTable').empty();
limit = 10 * (parseInt(start) + 1) > max_size ? max_size : 10 * (parseInt(start) + 1)
goFun(start * 10, limit);
});
EDIT:
to start directly with result, you can execute the first button like
$('.nav button')[0].click()
only put this at the end of your code
see fiddle
Take a look on that fork (https://jsfiddle.net/Kyrylo/2hbxmove/)
Instead focus I use button's disable/enable, but idea the same.
// keep in scope var current - ref to current page
// on nav btn click, prev, next
// remove disabled attr from current btn
$('#' + current).removeAttr('disabled');
// update current value, line below from onPrevClick handler
current = Math.max(current - 1 , 0);
// disable new current
$('#' + current).attr('disabled', 'disabled');

Javascript Sweet Alert and html link inside text

i have the following SweetAlert Code..
<script type="text/javascript" charset="utf-8">
$('.patient-details').click(function(e) {
e.preventDefault();
var name = $(this).attr('data-name');
var gender = $(this).attr('data-gender');
var age = $(this).attr('data-age');
var country = $(this).attr('data-country');
var state = $(this).attr('data-state');
var address = $(this).attr('data-address');
var report = $(this).attr('data-report');
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
});
});
</script>
The var report is a link and i need the link displayed in the modal. I tried html: true etc. html is no longer used. Instead use the content object. as doc says:
https://sweetalert.js.org/docs/#content
https://sweetalert.js.org/guides/
But i as a newbie is unable to make sense out of it.
Requesting help on how to display the link in the modal and the link to be opened in new window.
Update:
Since the solutions provided were not working i used another approach using html to resolve it. Need to remove text, else text will be default. Codepen link:
https://codepen.io/pamela123/pen/GOJZgo
Found this answer here, all credits to
Tristan Edwards
const el = document.createElement('div')
el.innerHTML = "Here's a <a href='http://google.com'>link</a>"
swal({
title: "Hello!",
content: el,
})
As the doc says, html is deprecated and no longer works.
They have replaced html with content, which is not a string any longer, but an Object.
This content object looks like this :
content: {
element: "input",
attributes: {
placeholder: "Type your password",
type: "password",
}
}
So I guess you can build your own link like this :
content: {
element: "a",
attributes: {
href : report
}
}
...and then simply pass the content object to swal :
swal({
content: {
element: "a",
attributes: {
href : report
}
}
})
Note that this is untested, I'm not sure if element:"a" works. But anyway, the doc gives a better way :
var slider = document.createElement("input");
slider.type = "range";
swal({
content: slider
});
So you can create a link this way :
var link = document.createElement("a");
link.href= report;
swal({
content: link
});
As an aside, you can heavily optimize the code you provided in your question by caching $(this) (which is expensive to create) and reuse it. Also, .attr("data-x") has a shorthand, .data("x").
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var state = $this.data('state');
var address = $this.data('address');
var report = $this.data('report');
OR even better :
var attributes = $(this).data()
which gives an object containing all your data attributes. Which you can then reach using :
text: "Gender: " + attributes['gender'] +"\n" + "Age: " + attributes['age'] +"\n" + "Country: " + attributes['country'] +"\n" + "State: " + attributes['state'] +"\n" + "Address: " + attributes['address'] +"\n" + "Report: " + attributes['report']
Or in ES6 :)
text: `Gender: ${attributes['gender']}\n
Age: ${attributes['age']}\n
Country: ${attributes['country']}\n
State: ${attributes['state']}\n
Address: ${attributes['address']}\n
Report: ${attributes['report']}`
As Jeremy Thille found out in his commentary on Oct. 31 '17 at 10:36:
You do not need to use the option "content" for a simple link in the text.
The option "text" can only display pure text, no html.
However, the option "html" can display html.
Not to be confused with the old version SweetAlert 1.X: There you had to set html = true.
In SeewtAlert2, the html is set directly in the "html" option. Do not use option "text" in this case.
Works fine in sweetAlert.version = '6.9.1';
Example of Jeremy Thille:
$('.patient-details').click(function(e) {
e.preventDefault();
var $this = $(this)
var name = $this.data('name');
var gender = $this.data('gender');
var age = $this.data('age');
var country = $this.data('country');
var address = $this.data('address');
var report = $this.data('report');
swal({
title: name,
html:
"Gender: " + gender +"<br>" +
"Age: " + age +"<br>" +
"Country: " + country +"<br>" +
"Address: " + address +"<br>" +
"Report: " + report +"<br>" +
"<a href='report'>Report</a> " +
"and other HTML tags"
});
});
https://codepen.io/jeremythille/pen/wPazMw
Why not try the following (I have never used sweet alert, but after reading the documentation this is what I would try)
var link= document.createElement("a");
link.href = report // or link.setAttribute("href", report)
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
content:link
});
});
Or
swal({
title: name,
text: "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "State: " + state +"\n" + "Address: " + address +"\n" + "Report: " + report,
confirmButtonColor: "#00B4B4",
imageUrl: "images/avatar/user.png",
content:{
element:"a",
attributes:{
href:report
}
}
});
});
hope that helps
If you are not still able to find a solution, I tried recreating the modal
https://codepen.io/AJALACOMFORT/pen/zPGqNe?editors=0010
window.onload= function(){
var that = $(".patient-details")
var name = $(that).attr('data-name');
var gender = $(that).attr('data-gender');
var age = $(that).attr('data-age');
var country = $(that).attr('data-country');
var address = $(that).attr('data-address');
var report = $(that).attr('data-report');
//creates h2
var h2 = document.createElement("h2")
//adds text
h2.innerHTML = name
//creates p tag
var p = document.createElement("p")
p.innerHTML = "Gender: " + gender +"\n" + "Age: " + age +"\n" + "Country: " + country +"\n" + "Address: " + address +"\n" + "Report: " + report
//creates button
var button = document.createElement("button")
//adds the onclick function
button.setAttribute("onclick", "callbutton(event)")
button.innerHTML ="ok"
button.className += "confirm"
var link = document.createElement("a")
link.setAttribute("href", report)
link.innerHTML ="Link"
link.className += "report-link"
//appends all the elements into the mymodal div
var modal = document.getElementById("modal-inner")
modal.appendChild(h2)
modal.appendChild(p)
modal.appendChild(link)
modal.appendChild(button)
}
//listens to click event of the checkbox
function callbutton(){
document.getElementById("checkboxabove").checked = false;
}
Hopefully it helps. (Note I did not use the same transition effect like in sweet alert, so adjust as you please)

How to leave a placeholder within a variable to be filled later using Javascript?

On paper this paper this seems like a very simple operation, but for some reason Javascript does not seem to like it. Basically I have the following code:
var news = "<b>" + place_name + ", " + county + ""<img id = 'centre' src=" + picture + ">" + "</b><ul><br>";
The general idea is that picture is a variable that will be filled later via:
news.picture = entry2.picture;
which is a link to provide to the img source. However, when I do:
console.log(news.picture);
The variable remains undefined. Is this the correct way to go about things?
That's not the way you are supposed to do that. You have to have your variables set and then you can construct a string like that.
What you need now, is basically a function, like this:
var createNews = function(place_name,county,picture) {
return "<b>" + place_name + ", " + county + "<img id = 'centre' src=" + picture + ">" + "</b><ul><br>";
}
var news = createNews("Place","county","pic.jpg");
console.log(news);
Or you can do it like this, if you prefer:
var createNews = function(obj) {
return "<b>" + obj.place_name + ", " + obj.county + "<img id = 'centre' src=" + obj.picture + ">" + "</b><ul><br>";
}
var news = {
place_name : "Someplace",
county : "Somewhere",
picture : "foo.png"
};
var newsItem = createNews(news);
console.log(newsItem);
news is a variable made out of strings and variables.
So you cant use news.picture.
Though you can make the variable a function object.
var news = function() }
this.picture = "something";
this.getString = function() {
return this.picture+"some string";
};
};
Then you can get and set the picture variable inside news with news.picture and get the string with news.getString().

Checking for a value in an Array inside of a JSON file

I have a JSON file for which I have created a jQuery function to find matching values and and display them in a div. I'm not quite sure how to compare a single value within the activitiesarray in the JSON file. It only seems to return the entire array.
How do I check through each resortin the JSON file and see if one of the values in the activities array inside the JSON file contains a specific value like scuba diving
JavaScript:
var destination = $('option:selected', "#destination").attr('value');
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value');
var date = $('option:selected', "#date").attr('value');
var price = $('option:selected', "#price").attr('value');
$.getJSON('resort.json', function(data) {
$.each(data.resorts, function(key, val) {
if (destination == val.destination) {
if (comfortLevel == val.comfortLevel || activties == val.activities || date == val.startDate || price > val.price) {
$("#resortData").html("<img src= "+val.picture+" class='miniPic'> Destination: "+ val.destination + "<br>" + "Name: " + val.name + "<br>" +"Location: "
+ val.location + "<br>" + "Comfort: " + val.comfortLevel + " Star <br>" + "Activities: " + val.activities + "<br>" + "Price: £"
+ val.price + "<br>" + "Start Date: " + val.startDate + "<br>" + "End Date: " + val.endDate + "<br>" + "Description: " + val.short_description
+ "<br><br>" + "<a href=':" + val.url +"'>Click HERE for more info</a>");
}
}
});
});
resort.JSON:
{
"resorts": [
{
"id":"resort1",
"destination":"Carribean",
"name":"Les Boucaniers",
"location":"Martinique",
"comfortLevel": "4",
"activities":["water skiing", "tennis", "scuba diving", "kitesurf", "spa"],
"price":1254,
"startDate":"2016-01-01",
"endDate":"2016-12-31",
"short_description":"The resort of Les Boucaniers is located on the laid-back beach-covered south coast of the island, and is perfectly placed for Martinique holidays that are both relaxing and awe-inspiring.",
"picture":"images/resort1pic1small.jpg",
"long_description":"A divers' paradise in the Baie du Marin, a legendary spot.<br>Its bungalows are discreetly lodged in a tropical garden beside the white sand beach in superb Marin Bay. A magical site where you can enjoy a taste of everything, alone or with family or friends. Try water sports and the magnificent Club Med Spa*. You'll be enchanted by the exotic flavours of the local cuisine and the joyful spirit of the Caribbean.",
"url":"resorts/resort1.html"
},
{
"id":"resort2",
"destination":"Indian Ocean",
"name":"La Plantation d'Albion",
"location":"Mauritius",
"comfortLevel": "5",
"activities":["kids club","golf", "scuba diving", "flying trapeze", "tennis", "sailing", "spa"],
"price":2062,
"startDate":"2016-01-01",
"endDate":"2016-12-31",
"short_description":"Beautifully located in one of the last remote creeks on the island, La Plantation d'Albion Club Med welcomes the most demanding of guests into a world of supreme refinement.",
"picture":"images/resort2pic1small.jpg",
"long_description":"In a remote beauty spot, savour the luxury of Mauritian lifestyle. <br> The idyllic natural setting is enhanced by the sublime decor designed by Marc Hertrich and Nicolas Adnet, and the Resort's top-end comfort is perfectly reflected in its beautifully spacious rooms. The exceptional CINQ MONDES Spa* and luxurious overflow pool add an ideally Zen touch.<br> The Resort is entirely devoted to fulfilling its guests' desires and offers discreet, personal service in its swimming areas, bars and 'Table Gourmet' restaurants.",
"url":"resorts/resort2.html"
}
]}
How do I check through each resortin the JSON file and see if one of
the values in the activities array inside the JSON file contains a
specific value like scuba diving
Use indexOf() on the activities array.
NB there's a typo (activties ) here: if (comfortLevel == val.comfortLevel || activties == val.activities ...
A little tricky, but sometimes a RegExp helps in this type of situations and saves a lot of code:
var escape = /[.?*+^$[\]\\(){}|-]/g;
var destination = $('option:selected', "#destination").attr('value').replace(escape, "//$&");
var comfortLevel = $('option:selected', "#comfortLevel").attr('value');
var activities = $('option:selected', "#activities").attr('value').replace(escape, "//$&");
var date = $('option:selected', "#date").attr('value').replace(escape, "//$&");
var price = $('option:selected', "#price").attr('value');
$.get('resort.json', function(data) {
var json = JSON.parse( data.match(new RegExp('(\{[^\{\}]*?"destination"\s*\:\s*"' + destination + '"[^\}]*(?:"comfortLevel"\s*\:\s*"' + comfortLevel + '"|"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]|"date"\s*\:\s*"' + date + '"|"price"\s*\:\s*(?:' + "[0-" + price.split("").join("]?[0-") + "]?" + '))[^\{\}]*?\})'))[0] );
$("#resortData").html("<img src= "+json.picture+" class='miniPic'> Destination: "+ json.destination + "<br>" + "Name: " + json.name + "<br>" +"Location: "
+ json.location + "<br>" + "Comfort: " + json.comfortLevel + " Star <br>" + "Activities: " + json.activities + "<br>" + "Price: £"
+ json.price + "<br>" + "Start Date: " + json.startDate + "<br>" + "End Date: " + json.endDate + "<br>" + "Description: " + json.short_description
+ "<br><br>" + "<a href=':" + json.url +"'>Click HERE for more info</a>");
});
The specific piece of RegExp to test if an activities is contained in the Array is this:
'"activities"\s*\:\s*\[[^\]]*"' + activities + '"[^\]]*\]'

Getting hourly info from weather API

I am trying to access hourly info from a weather API.
The problem is its not quite working for me, and I am not 100% sure of how to gain access to the information.
This is the site I am working with, and the page on the hourly info.
http://www.wunderground.com/weather/api/d/docs?d=data/hourly&MR=1
I have a strong feeling it has to do with the way the access to variables...
This is my code:
<script>
jQuery(document).ready(function($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType : "jsonp",
success : function(parsed_json) {
//get the hourly info -- cant get hourly to work...
var month = parsed_json['hourly_forecast']['FCTTIME']['mon_padded'];
var day = parsed_json['hourly_forecast']['FCTTIME']['mday_padded'];
var year = parsed_json['hourly_forecast']['FCTTIME']['year'];
var time = parsed_json['hourly_forecast']['FCTTIME']['civil'];
var updated = month + "/" + day + "/" + year + " " + time;
var weather = parsed_json['hourly_forecast']['condition'];
var temp = parsed_json['hourly_forecast']['temp']['metric'];
var humid = parsed_json['hourly_forecast']['humidity'];
var wind_direction = parsed_json['hourly_forecast']['wdir']['dir'];
var wind_speed = parsed_json['hourly_forecast']['wspd']['metric'];
var wind_string = wind_direction + " " + wind_speed + " Km/h";
document.getElementById("weather").innerHTML = weather;
document.getElementById("temp").innerHTML = temp;
document.getElementById("hum").innerHTML = humid;
document.getElementById("wind").innerHTML = wind_string;
}
});
});
</script>
If you open the JSON file from that URL you will see that it does not contain "hourly_forecast" or "FCTTIME".
EDIT:
Open up the JSON file that you are downloading and look at what fields it is sending back to you. JQuery already does the hard part and parses it into an object model. Also, the javascript debuggers in Chrome is great at showing you the JSON object model. You can just set a breakpoint at the beginning of the "success" function and use the "Local Variables" window to explore the JSON object.
Here's your code after I updated it to use the correct field names from the JSON file...
<script>
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.wunderground.com/api/6368023a57d122c7/geolookup/conditions/q/DominicanRepublic/Barahona.json",
dataType: "jsonp",
success: function (parsed_json) {
var current_observation = parsed_json.current_observation;
var lastUpdated = current_observation.observation_time;
var weather = current_observation.weather;
var temp = current_observation.temp_c;
var humid = current_observation.relative_humidity;
var wind_direction = current_observation.wind_dir;
var wind_speed = current_observation.wind_kph;
var wind_string = wind_direction + " " + wind_speed + " Km/h";
alert("Weather: " + weather + "\n"
+ "Temp: " + temp + "\n"
+ "Humidity: " + humid + "\n"
+ "Wind: " + wind_string + "\n"
+ lastUpdated
);
}
});
});
</script>

Categories

Resources