using javascript to load json data from google maps - javascript

So, this is the code I have, console.log gives me the right value, but the function doesn't return the value, even if the return is inside the timeout. I must be doing something wrong.
function countyfinder(address){
var rr =$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address.replace(" ", "%20")).done(function(data) {
var county = data.results[0].address_components[3].short_name;
//return county;//data is the JSON string
});return rr;};
function calculatetax(address, price){
var j = countyfinder(address);
setTimeout(function(){var k = j["responseJSON"]['results'][0]['address_components'][3]['short_name'];
console.log(k);//return k won't work in here either
}, 1000); return k
};

this is what I ended up with:
var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
function getCounty(address) {
var country;
var baseApiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
var query = "?address=" + encodeURIComponent(address);
var queryUrl = baseApiUrl + query;
$.ajax({
url: queryUrl,
async: false,
dataType: 'json',
success: function(data) {
county = gmapsExtractByType(data, "administrative_area_level_2 political");
}
});
return countr.long_name;
}
function gmapsExtractByType(json, type) {
return json.results[0].address_components.filter(function(element) {
return element.types.join(" ") === type;
})[0];
}
console.log( getCounty("100 wacko lane ohio") );
I had to use a synchronous request by changing some settings in the ajax request. The drawback of this is that the browser will be locked up until you get a request response, which can be bad on a slow connection or a connection with an unreliable server. With google, most of the time, I don't think that will happen.

Related

Delay Ajax Function per request with Google Maps API

I want to get some data about places using the Google Places API.
Thing is, I want to get data from more than 1000 records, per city of the region I'm looking for.
I'm searching for pizzeria, and I want all the pizzerias in the region I've defined. So I have an array like this:
['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse']
My objective is to make a single request, then wait 3sec(or more), and then process the second request. I'm using Lodash library to help me iterate.
Here is my code:
function formatDetails(artisan){
var latitude = artisan.geometry.location.lat;
var longitude = artisan.geometry.location.lng;
var icon = artisan.icon;
var id = artisan.id;
var name = artisan.name;
var place_id = artisan.place_id;
var reference = artisan.reference;
var types = artisan.types.toString();
$('#details').append('<tr>'+
'<td>'+latitude+'</td>'+
'<td>'+longitude+'</td>'+
'<td>'+icon+'</td>'+
'<td>'+id+'</td>'+
'<td>'+name+'</td>'+
'<td>'+place_id+'</td>'+
'<td>'+reference+'</td>'+
'<td>'+types+'</td>'+
'</tr>');
}
var getData = function(query, value){
$.ajax({
url: query,
type: "GET",
crossDomain: true,
dataType: "json",
success: function(response) {
var artisan = response.results;
console.log(artisan);
for (var i = 0; i < artisan.length; i++){
formatDetails(artisan[i]);
setTimeout(function(){console.log('waiting1');},3000);
}
setTimeout(function(){console.log('waiting2');},3000);
},error: function(xhr, status) {
console.log(status);
},
async: false
});
}
$(document).ready(function(){
var places =
['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];
_.forEach(places, function(value, key) {
var proxy = 'https://cors-anywhere.herokuapp.com/';
var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
var query = proxy + target_url;
getData(query, value);
});
});
I've tried a lot of solutions I found on stackoverflow, but no one were working, or I might have done them wrong.
Thanks for your help!
The fact that $.ajax returns a Promise makes this quite simple
Firstly, you want getData to return $.ajax - and also get rid of async:false
var getData = function(query, value) {
return $.ajax({
url: query,
type: "GET",
crossDomain: true,
dataType: "json",
success: function(response) {
var artisan = response.results;
for (var i = 0; i < artisan.length; i++){
formatDetails(artisan[i]);
}
},error: function(xhr, status) {
console.log(status);
}
});
}
Then, you can use Array.reduce iterate through the array, and to chain the requests together, with a 3 second "delay" after each request
Like so:
$(document).ready(function(){
var places = ['Pizzeria+Paris','Pizzeria+Marseille','Pizzeria+Nice','Pizzeria+Toulouse'];
places.reduce((promise, value) => {
var proxy = 'https://cors-anywhere.herokuapp.com/';
var target_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+value+'&key=AIzaSyAClTjhWq7aFGKHmUwxlNUVBzFpIKTkOrA';
var query = proxy + target_url;
return promise.then(() => getData(query, value))
// return a promise that resolves after three seconds
.then(response => new Promise(resolve => setTimeout(resolve, 3000)));
}, Promise.resolve()) /* start reduce with a resolved promise to start the chain*/
.then(results => {
// all results available here
});
});
The most effective answer is the one above from #jaromandaX.
Nevertheless, I also found a workaround with Google Chrome, which will help you to not get your hands dirty with promises.
On Chrome:
1. Open Console
2. Go to network tab
3. Near the options "preserve log" and "disable cache", you have an option with an arrow where you will see the label "No throttling".
4.Click on the arrow next to the label, then add.
5. You will be able to set a download and upload speed, and most important, delay between each request.
Kaboom, working with my initial code.
Nevertheless, I changed my code to fit the above answer, which is better to do, in terms of code, speed, etc..
Thanks

Fill array by multiple AJAX requests, then pass array to another function

(My solution below)
I have several HTML elements with class .canvas-background of which information is stored in the database. I want to get the information of each element and process it via JavaScript. But somehow I can't pass the response of the AJAX request to another function. Here is what I've tried:
function initTabs() {
var tabs = loadTabInformation();
console.log(tabs); // (1)
// do something else
}
function loadTabInformation() {
var requests = new Array();
var tabs = new Object();
var counter = 0;
$(".canvas-background").each(function () {
var tabNumber = $(this).data("tab-number");
var request = $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(tabNumber),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
})
.done(function (response) {
tabs[counter++] = response;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error in loadTabInformation()");
console.log(textStatus);
console.log(errorThrown);
});
requests.push(request);
});
$.when.apply($, requests).done(function () {
console.log(tabs); // (2)
return tabs;
});
}
At (1) I get undefined, but at (2) everything seems to be alright.
THE SOLUTION:
Thanks to the answer and the link in the comment #Kim Hoang provided I got this working. The clue seemed to put the done() function in the calling function, that is initTabs() in my case. Another thing I got wrong was to try to do the logic that should be executed after the AJAX requests had finished outside the done callback function. They must be inside (makes sense, if you think about it). And a lot of conosle output helped, to see what function returns what kind of object.
function initTabs() {
var tabInfoRequest = loadTabInfo();
tabInfoRequest[0].done(function() {
var results = (tabInfoRequest[1].length > 1) ? $.map(arguments, function(a) { return a[0]; }) : [arguments[0]];
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
});
}
function loadTabInfo() {
var tabNumbers = new Array();
$(".canvas-background").each(function () {
tabNumbers.push($(this).data("tab-number"));
});
var requests = $.map(tabNumbers, function (current) {
return $.ajax({
type: 'POST',
url: '../db/GetTabInformation.ashx',
data: String(current),
dataType: 'json',
contentType: 'text/plain; charset-utf-8'
});
});
var resultObject = new Object();
resultObject[0] = $.when.apply($, requests);
resultObject[1] = requests;
return resultObject;
}
Note: I only did the resultObject-thing because I needed the array requests in the initTabs() function.
Thank you very much for helping me!
You do not return anything in loadTabInformation, so of course you will get undefined. You should do it like this:
function loadTabInformation() {
...
return $.when.apply($, requests);
}
function initTabs() {
loadTabInformation().done(function (tabs) {
console.log(tabs); // (1)
// do something else
});
}

Set Value from JSON via AJAX

I'm using Github Gists for a web playground I'm making as a side project. I load two json files into the editor. 1 handles all the libraries (jquery, bootstrap, etc:) and another for the users settings (fontsize, version, etc:)
So anyway I have this JSON named settings
var settings = gistdata.data.files["settings.json"].content
var jsonSets = JSON.parse(settings)
I parse and attempted to grab an object from the JSON and set it as a value of a input textbox.
Now console.log(jsonSets.siteTitle) works perfectly fine
but when I try to change the input dynamically...
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
The problem is it's not actually applying the value!
The only way I've been able to successfully apply the value is...
setTimeout(function() {
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
}, 5000)
Which is ridiculously slow.
Does anyone know why it's not applying the value?
in addition.
How can I solve this problem?
var hash = window.location.hash.substring(1)
if (window.location.hash) {
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp"
}).success(function(gistdata) {
var libraries = gistdata.data.files["libraries.json"].content
var settings = gistdata.data.files["settings.json"].content
var jsonLibs = JSON.parse(libraries)
var jsonSets = JSON.parse(settings)
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value)
})
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle).trigger("change")
$("[data-value=version]").val(WeaveVersion).trigger("change")
$("[data-editor=fontSize]").val(editorFontSize).trigger("change")
$("[data-action=sitedesc]").val(WeaveDesc).trigger("change")
$("[data-action=siteauthor]").val(WeaveAuthor).trigger("change")
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
My problem was actually related to localStorage.
I cleared it localStorage.clear(); ran the ajax function after and it solved the problem.
var hash = window.location.hash.substring(1)
if (window.location.hash) {
localStorage.clear()
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp",
jsonp: "callback"
}).success(function(gistdata) {
var htmlVal = gistdata.data.files["index.html"].content
var cssVal = gistdata.data.files["index.css"].content
var jsVal = gistdata.data.files["index.js"].content
var mdVal = gistdata.data.files["README.md"].content
var settings = gistdata.data.files["settings.json"].content
var libraries = gistdata.data.files["libraries.json"].content
var jsonSets = JSON.parse(settings)
var jsonLibs = JSON.parse(libraries)
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle)
$("[data-value=version]").val(WeaveVersion)
$("[data-editor=fontSize]").val(editorFontSize)
$("[data-action=sitedesc]").val(WeaveDesc)
$("[data-action=siteauthor]").val(WeaveAuthor)
storeValues()
// Return settings from the json
$(".metaboxes input.heading").trigger("keyup")
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value).trigger("keyup")
})
// Set checked libraries into preview
$("#jquery").trigger("keyup")
// Return the editor's values
mdEditor.setValue(mdVal)
htmlEditor.setValue(htmlVal)
cssEditor.setValue(cssVal)
jsEditor.setValue(jsVal)
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}

Test object has a value in it or not in javascript

I have one class in javascript :
function Quotation(){
if(typeof Quotation.instance === 'object'){
return Quotation.instance;
}
Quotation.instance = this;
var self = this;
this.getQuotation = function(customerID,numRow){
var result = "";
var urlDefault = "mysite.com/getDefaultQuote" + "?id="+ customerID +"&count=" + numRow;
var url = "mysite.com/getQuote" + "?id="+ customerID +"&count=" + numRow;
$.ajax({
url:url,
type:type,
dataType:datatype,
contentType: contenttype,
data : JSON.stringify(data),
success:function(res){
result = res;
},
error:function(res){
result="";
},
async : false
});
return result;
};
}
This is where my view call Quotation object :
var quotation = new Quotation();
var HomeView = Backbone.View.extend({
initialize: function() {
},
render: function(){
console.log(quotation.getQuotation(10,12));
}
});
I want to test in getQuotation :
if quotation.getQuotation(10,12) has value in it, then getQuotation will take url = "mysite.com/getQuote" as an ajax request URL.
Otherwise if quotation.getQuotation(10,12) no record, then getQuotation will take urlDefault = "mysite.com/getDefaultQuote";.
Here the result in the console :
Any help is much appreciated.
You should check res inside the success callback and perform an extra AJAX request to load the default quote when res is null.
I would probably implement this logic server-side so that you always perform a single request.

Javascript variable scope hindering me

I cant seem to get this for the life of me. I cant access the variable "json" after I calll the getJson2 function. I get my json dynamically through a php script, and that works. But then its gone. there is a sample that I use as a guide at The InfoVis examples where the json is embedded in the init function. i am trying to get it there dynamically.
<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport,animate,json;
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
(function() {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
debugger;
var Log = {
elem: false,
write: function(text){
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
debugger;
this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(){
json = getJson2();
//init data
var st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
//set duration for the animation
duration: 800,
//set animation transition type ..................
function getJson2()
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
return data;
})
};
getJson2() doesn't return anything. The callback function to $.get() returns something, but nothing is listening for that return.
It sounds like you want synchronous loading instead. $.get() is just shorthand for this $.ajax() call: (See docs)
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
And $.ajax() supports more features, like setting async to false.
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
// data !
}
});
Which means, getJson2 then becomes:
function getJson2()
{
var cd = getParameterByName("code");
var jsonData;
$.ajax({
url: "tasks.php?code="+cd,
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
return jsonData;
};
var myJsonData = getJson2();
Or still use $.get async style, and use callbacks instead.
function getJson2(callback)
{
var cd = getParameterByName("code");
$.get("tasks.php?code="+cd, function(data){
callback(data);
});
};
getJson2(function(data) {
// do stuff now that json data is loaded and ready
});
The $.get call is asynchronous. By the time you call return data;, the function has already long since returned. Create a variable outside of your function's scope, then in the $.get callback handler, assign data to that variable.
var json;
function getJson2(){
// ...
$.get(...., function(response){
json = response;
}
});
Alternatively, you could do a sychronous Ajax call, in which case returning your data would work (but of course would block script execution until the response was recieved). To accomplish this, see the asynch argument to jQuerys $.ajax function.
A jQuery $.get call is asynchronous and actually returns a promise, not the data itself.
An elegant way to deal with this is to use the then() method:
$.get(...).then(function(data){...});
Alternately, change your ajax settings to make the call synchronous.
$.get("tasks.php?code="+cd, function(data){
return data;
})
$.get is asynchroneous. So your value is never returned. You would have to create a callback.
The same question appears here:
Return $.get data in a function using jQuery

Categories

Resources