javascript API call results in old data - javascript

I have a weather web api,which I need to show weather report of current city in website.Whenever the code calls in the API, it results only in old data.Data never changes and when I run the web API URL on the browser it results exactly what I want.
Please help me what could be the reason for the cached data.
webAPI
http://api.openweathermap.org/data/2.5/weather?lat=26.894049&lon=80.942686&mode=json
my code
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + 'mode=json&rand=' + Math.random(), function (data) {
var wind = {};
var temp = {};
wind = data.wind;
temp = data.weather;
var clouds = '%' + data.clouds.all;
var description = data.weather[0].description;
var temp = data.main.temp - 273.15;
var humidity = data.main.humidity + '%';
var icon = data.weather[0].icon;
weatherImg = "<img height=\"45\" width=\"45\" style=\"border: medium none; width: 45px; height: 45px;position:relative;top:-10px; background: url('http://openweathermap.org/img/w/" + icon + ".png') repeat scroll 0% 0% transparent;\" alt=\"title\" src=\"http://openweathermap.org/images/transparent.png\">";
document.getElementById('weatherImg').innerHTML = weatherImg;
document.getElementById('current_temp').innerHTML = (temp) + '°C';
document.getElementById('current_wind').innerHTML = ' ; ' + wind.speed + 'Km/h';
document.getElementById('city_name').innerHTML = data.name;
});

tested your code working fine for me some time api response is slow but other than that every thing looks ok to me
htttp://jsfiddle.net/navneetccna/un2u5j0v

Shouldn't the url in your script prefix mode with &. You should throw this in a fiddle / be more specific. You say you're getting old data. Are you getting an old JSON response that doesn't change at all, or infrequently?

Related

Pushing Woocommerce orders to Google Sheets

I have setup a woocommerce website, used for delivery of meals from different restaurants in my area. I have tried to setup an automatic transfer of the order data from the json file straight to a Google sheet our drivers use, but I have found myself encountering errors in Google Script everytime woo's webhook fires, and not being able to detect the issue.
Here is my google script code
//this is a function that fires when the webapp receives a GET request
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
//this is a function that fires when the webapp receives a POST request
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var order_number = myData.number;
var order_address = myData.billing.address_1;
var item = ""
var url = "https://fivestars-delivery.com/mon-compte//driver-dashboard/?orderid=" + order_number;
for (var i = 0; i < myData.line_items.length(); ++i) {
item += myData.line_items[i].product_id + "\n"
total += parseInt(myData.line_items[i].total)
}
var fees = ""
// var feesTotal = 0
for (var i = 0; i < myData.fee_lines.length(); ++i) {
// convertir en entier
// feesTotal += parseInt(myData.fee_lines[i].total)
fees += myData.fee_lines[i].amount + " " + myData.fee_lines[i].name + " - " + myData.fee_lines[i].total + "\n"
}
var discount = myData.discount_total
// nom client
var nomClient = myData.first_name + " " + myData.last_name
var order_total = myData.total;
var payment_method = myData.payment_method_title;
var phone = myData.billing.phone
var note = myData.billing.address_2 + "\n" + myData.customer_note
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.appendRow([order_number, " ", " ", " ",order_address, " ", "Attente d'envoi",url, order_total, payment_method, nomClient, phone, note, item + fees + discount, ]);
}
-I set up a WooCommerce API and webhook using the api's secret key
-Entered my web application's URL as delivery URL in the webhook
I cannot find out what is wrong and none of the situations I found online have found no help so far.
The variable total is never created, but it is used within the for loop.

Reverse geocoding doesn't work on mobile device

I'm writing a small web page and one of my functionalities is to take a photo and write the location (street and city) instantly on the taken photo.
Here's my code:
window.cb = function cb(json) {
document.getElementById('city').value = json.address.road+ " " + json.address.postcode + ',' + json.address.city;
}
window.search = function search(x,y) {
var s = document.createElement('script');
s.src = 'http://nominatim.openstreetmap.org/reverse?json_callback=cb&format=json&lat=' + x + '&lon=' + y + '&addressdetails=1&accept-language=en-US';
document.getElementsByTagName('head')[0].appendChild(s);
};
....
search(x,y);
setTimeout(function(){
var city = document.getElementById('city').value;
context.strokeText(city, 270, 260);
}, 2000);
It works fine on the desktop version, but fails when tried on mobile device. I tried setting the timeout to higher value - doesn't help.
Any suggestions would be appreciated.
Thanks.

Show a new GIF on each page visit or page reload

I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
var apiKey = '';
var url = '';
var data;
// console.log(position);
$.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {
$('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
$('.js-current-item2').html(data.currently.summary);
gif(data.currently.icon)
city(position.coords.latitude + "," + position.coords.longitude)
});
}
And here is the function for pulling images from GIPHY
function gif(status) {
var apiKey = '';
var url = 'http://api.giphy.com/v1/gifs/search?q=';
var query = status;
$.getJSON(url + query + apiKey, function(data) {
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
});
}
In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');

Multiple data from API not appearing in correct order-Tumblr and Last.fm

I have a list of my recent Tumblr audio posts coming in through the Tumblr API and with each post, an artist summary from the Last.fm API is attached. I have the data coming in correctly, but the audio posts are not showing up in chronological order. Every time I refresh the page, they appear in random order. I would like to have the most recent audio post appear at the top. Here is my code:
$(document).ready(function() {
var user = "nycxnc";
var key = "###";
var type = "audio";
var limit = "5";
var url = "https://api.tumblr.com/v2/blog/" + user +
".tumblr.com/posts/" + type + "?callback=?&filter=" + type +
"&limit=" + limit + "" + key + "";
$.getJSON(url, function(data) {
$.each(data.response.posts, function(i, item) {
var artist = item.artist;
var track = item.track_name;
var url2 =
"http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&track=" +
track + "&artist=" + artist +
"&api_key=###&autocorrect=1&format=json&callback=?";
$.getJSON(url2, function(data) {
$.each(data, function(i, item) {
artist_summary = item.bio.summary;
artist_image = item.image[4]["#text"];
$(".au-wrapper").append(
'<div class="audio-wrapper"><img src=' + artist_image +
'><div class="audio-meta"><span class="audio-title">' +
track + '</span><div class="audio-artist">' + artist +
'</div></div><div class="url">' + artist_summary +
'</div></div>');
});
});
});
});
});
How can I combine the data from two API in the correct order, if the second JSON url (Last.fm) is dependent on data from the Tumblr API? I'm new to Javascript and I'm creating this script as a learning experiment, so any help would be very appreciated. (: Thank you.

Map Route Direction Zoom to Segment

Basically I am trying to zoom to certain route segment when getting direction on OneMap. Here is the JavaScript codes where I trying to plot a route and zoom to certain route segment:
function getDirections() {
var routeData = new Route;
var from = document.getElementById('txtFrom').value
var to = document.getElementById('txtTo').value
//Draw out the line from the cordinate to another cordinate
routeData.routeStops = from + ";" + to;
//What type of mode will it do
routeData.routeMode = "DRIVE";
//can draw out untill the following coordiante
routeData.barriers = '36908.388637,35897.420831';
{
if (document.getElementById('CbAvoid').checked) {
routeData.avoidERP = "1";
}
else
routeData.avoidERP = "0";
}
routeData.GetRoute(showRouteData)
}
function showRouteData(routeResults) {
if (routeResults.results == "No results") {
alert("No Route found, please try other location.")
return
}
$('#divComputedDirection').show();
directions = routeResults.results.directions[0];
directionFeatures = directions.features;
var routeSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0, 0, 255, 0.5])).setWidth(4);
var mergedGeometry = new esri.geometry.Polyline()
mergedGeometry.addPath(routeResults.results.routes.features[0].geometry.paths[0])
OneMap.map.graphics.add(new esri.Graphic(mergedGeometry, routeSymbol));
//Display the total time and distance of the route
var htmlStr = "";
htmlStr += "<img class='close-image' onclick='closeDirectionResultDIV();' alt='close' src='img/closeDirectionResult.png' />";
htmlStr += "<span style='font-weight:bold;'><br /> Total distance: " + Math.round(directions.summary.totalLength) + "km" + "<br /> Total time: " + Math.round(directions.summary.totalTime) + "mins <br/></span>";
document.getElementById("divComputedDirection").innerHTML = htmlStr;
//List the directions and create hyperlinks for each route segment
for (var i = 0; i < directions.features.length; i++) {
var feature = directions.features[i]
document.getElementById("divComputedDirection").innerHTML += '<br>' + parseInt(parseInt(i) + 1) + ". " + feature.attributes.text + " (" + formatDistance(feature.attributes.length, "miles") + ", " + formatTime(feature.attributes.time) + ") " + '';
}
}
//Zoom to the appropriate segment when the user clicks a hyperlink in the directions list
function zoomToSegment(index) {
var segment = directionFeatures[index];
map.setExtent(segment.geometry.getExtent(), true);
if (!segmentGraphic) {
segmentGraphic = map.graphics.add(new esri.Graphic(segment.geometry, segmentSymbol));
}
else {
segmentGraphic.setGeometry(segment.geometry);
}
}
It did plot the route and show all the directions. But when I click on certain direction and zoom to segement, it throws me an error message which is Uncaught TypeError: Cannot call method 'getExtent' of undefined.
I wonder why is it so. Thanks in advance.
The root cause of your error is that you're trying to get the extent of a .geometry property that doesn't exist - that part is relatively easy. The problem, I think, is that you're looking for the geometry of each segment of the journey, and the return from OneMap's RouteTask doesn't give you that directly.
The geometry from the entire route is in
routeResults.results.routes.features[0].geometry.paths[0]
and the individual segments are in one of ESRI's fun compressed formats in the value:
routeResults.results.directions[x].features[y].compressedGeometry
There's some documentation and C# code for this compressed format here:
http://resources.esri.com/help/9.3/arcgisengine/ArcObjects/esrinetworkanalyst/INACompactStreetDirection_CompressedGeometry.htm
It should be relatively easy to port that C# code to JS if you really need the geometry of individual segments.
OneMap have a full working example here which shows how to process the results from the RouteTask, but unfortunately they don't attempt to extract the compressedGeometry field.
Edit: More sample code from ESRI here, with examples in C#/Java/Python.

Categories