David Colyer
David Colyer

Reputation: 23

Query Fusion Table from JavaScript function in API v1

I am trying to figure out how to use the new Fusion Table API v1 to query a table, from within a Javascript function. I want to be able to loop through the result, row by row, and do something else (in this case geocoding addresses) as I go.

I have the syntax for the query working OK. When I paste the http it into a browser it returns the correct result.

What I can’t figure out is how to make the request in the first place, and get the result where I can use it.

This post is close to what I’d like to do, but it uses the old API: http://www.reddmetrics.com/2011/08/10/fusion-tables-javascript-query-maps.html

function getData() {
    // Builds a Fusion Tables SQL query and hands the result to  dataHandler

    var queryUrlHead = 'https://www.googleapis.com/fusiontables/v1/query?sql=';
    var queryUrlTail = '&key={my key}';
    Table = {my table id};

    // write your SQL as normal, then encode it
    var query = "SELECT Address, Name FROM " + Table + " LIMIT 5";
    var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);

    var jqxhr = $.get(queryurl, dataHandler, "jsonp");
}

Maybe jquery is not needed with the new api?

Upvotes: 2

Views: 1987

Answers (1)

Odi
Odi

Reputation: 6916

The code you provided is okay, it works as expected (for me). I created a jsFiddle to show you an example usage of it.

All you need to do it specify a function called dataHandler as this is what you tell jQuery to use as a callback. I.e. the result of the jQuery call is, that it calls the function you specified.

To get started I suggest to make you Fusion Table public. That way you can explore the usage of the API without having to worry about authentication etc.

function dataHandler(response) {
    console.log(response);
    //do something with the data using response.rows
}

function getData() {
    // Builds a Fusion Tables SQL query and hands the result to  dataHandler

    var queryUrlHead = 'https://www.googleapis.com/fusiontables/v1/query?sql=';
    var queryUrlTail = '&key={my key}';
    Table = {my table id};

    // write your SQL as normal, then encode it
    var query = "SELECT Address, Name FROM " + Table + " LIMIT 5";
    var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);

    var jqxhr = $.get(queryurl, dataHandler, "jsonp");
}

If you just use console.log to analyze the response you get from Fusion Tables (press F12 in your browser to open the console/Developer Tools), you see that you get an object with a columns and a rows property, like that you can use the data the way you like. My example above simply prints a HTML table of the retrieved data.

In case your query has an error or is not accessible the error property is set with an according error message.

Upvotes: 1

Related Questions