Google Maps and Fusion Tables - google-maps

A map I created last year using Google Maps API V3 and Fusion Tables V1 has stopped functioning properly in the last week or so. I am not sure if I missed an update that has deprecated my code or if there's another explanation. In brief, the following code queries my fusion table and if a match is found it returns data for an info window. However, it is now returning false every time. The addInfoWindow() function is firing fine. The issue appears to be either in the query itself or the data that's returned. Additionally, the pin is dropping in the correct location on the map so the coordinates are not the issue.
This issue can be replicated by entering an address in the field. For demonstration purposes, 9132 Kingston Pike 37923 should return true. Clicking inside any polygon will return the intended results.
Thank you for any guidance you can provide.
// query
var script = document.createElement('script');
var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
url.push('sql=');
var query = "SELECT * FROM " +
tableid + " WHERE ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + coordinate.lat() + "," + coordinate.lng() + "), 0.001))";
var encodedQuery = encodeURIComponent(query);
url.push(encodedQuery);
url.push('&callback=addInfoWindow');
url.push('&key=' + apiKey);
script.src = url.join('');
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
// call back function
function addInfoWindow(data) {
infowindow.close();
initialize();
var rows = data['rows'];
if (rows)
{
console.log("inside if statement");
for (var i = 0; i < 1; i++)
{
console.log("inside for loop: " + rows[i][0]);
infowindow.setContent("<div style='width:250px;'><h2>"+ rows[i][1] + "</h2><p>The neighborhood contact in your area would love to hear from you! </p><p>Click <a href='https://cspctystn.infellowship.com/GroupSearch/ShowGroup/" + rows[i][0] + "' target='_blank'>here</a> to get their information.</p><p> </p><p>If you desire to communicate with Community Life staff, contact -- removed --.<p><br/><br/></div>");
//console.log(rows[i][1] + ": " + rows[i][0]);
infowindow.setPosition(coordinate);
map.setCenter(coordinate);
map.setZoom(15);
infowindow.open(map);
}
}
else
{
console.log("error");
infowindow.setContent("<div style='width:250px;'><h2>Oops!</h1><p> It seems we don't have a neighborhood contact in your area.</p><p>Please communicate with our <a href='http://www.cspc.net/communitylife' target= '_blank' >Community Life</a> staff for more information. -- removed --<p></div>");
infowindow.setPosition(coordinate);
map.setCenter(coordinate);
map.setZoom(15);
infowindow.open(map);
}
}

Related

Google Apps Script cache stopped working today

I used Google Apps Script Cache's putAll() for 21600 seconds. It has been working for months today just stopped working - all get from cache return null. The script reads a .csv file with about 90K entries, remove unwanted chars then caches using putAll() method. I tested the same file with the same script in my Dev's project it works fine. So somehow it does not work in my Production project. The code exactly the same, below:
My production's project id: Vendor Retainer GAS - project-id-5629958634838222671
There is no errors reported.
function cacheVendorList() {
var dataFilesFolder = DriveApp.getFolderById(dataFileFolderId);
var fileIt = dataFilesFolder.getFilesByName("VendorFile.csv");
if (fileIt != null && fileIt.hasNext()) {
var vendorFile = fileIt.next();
var keyValueStr = "{" + vendorFile.getAs(MimeType.PLAIN_TEXT).getDataAsString().
replace(/SAP,NAME,CMPY,CURRENCY/,'99,Test').
replace(/[^a-zA-Z0-9 ,\n]/g,' ').
replace(/$/mg,'",').
replace(/^\d+,/mg,
function(x) {
return '"' + x.substring(0,x.length-1) + '": "';
}).
replace(/D ",\n",$/,'D "') + "}";
//dataFilesFolder.createFile("VendorFile.txt", keyValueStr, MimeType.PLAIN_TEXT);
//Logger.log(keyValueStr);
var keyValObj = eval("(" + keyValueStr + ")");
// create a new vendor cache
vendorCache.putAll(keyValObj, 21600); // 21600 cache it for 6 hours
Logger.log("0000010100: " + vendorCache.get("0000010100"));
Logger.log("0090000435: " + vendorCache.get("0090000435"));
Logger.log("Got it");
}
}

Google MAP API - Status code : ERROR

I built a hybrid application using 3rd party container for iPhone application. We are getting ERROR status code in Production, but we are not able to able to reproduce the ERROR status code in DEV/QA. Can anyone help to find out when Google returns status code as ERROR ? I tried providing wrong address information, without any value, but it always returns some latitude and longitude during my test.
<html>
<head>
<title>WOM</title>
<meta charset="utf-8">
<!-- Apple metatags -->
<script>
function loadGoogleScript(clientId) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?client=valid_client_id&v=3.21&' +
'callback=initialize';
//script.src='http://maps.googleapis.com/maps/api/js?sensor=false';
document.body.appendChild(script);
console.log('Google initialization done ');
}
function initialize() {
var geocoder = new google.maps.Geocoder;
var i;
var componentRestrictions = { country: 'CA' };
var count = 0;
for( i = 0; i < 15 ; i++) {
geocoder.geocode({'address':'Valley Ranch Parkway W, MA','componentRestrictions':componentRestrictions},function(results, status){
try {
if (status == google.maps.GeocoderStatus.OK) {
var lat = ""+results[0].geometry.location.lat();
var long = ""+results[0].geometry.location.lng();
console.log("count = " + count++ + "lat = " + lat + "long = " + long);
}
else{
console.log("count = " + count++ + " status = " + status);
}
} catch(e){
console.log(" exception e " + e);
}
});
}
}
</script>
</head>
<body onload='loadGoogleScript()'>
</body>
</html>
Status Codes
The "status" field within the Geocoding response object contains the status of the request, and may contain debugging information to help you track down why geocoding is not working. The "status" field may contain the following values:
"OK" indicates that no errors occurred; the address was successfully parsed and at least one geocode was returned.
"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address.
"OVER_QUERY_LIMIT" indicates that you are over your quota.
"REQUEST_DENIED" indicates that your request was denied.
"INVALID_REQUEST" generally indicates that the query (address, components or latlng) is missing.
"UNKNOWN_ERROR" indicates that the request could not be processed due to a server error. The request may succeed if you try again.

Trying to restart my Twitch API from scratch. Not sure how to get my response

I'm in the process of redesigning my website, and with this I wanted to update/improve the various scripts involved. One such script is a call to the Twitch API for a set group of streamers, then displaying who's online and, if any are, displaying the first live stream and allow the user to switch between them.
My original script, which works great, was originally constructed by somebody here on StackOverflow. The problem is that instead of guiding me to a usable answer, they just rewrote my code to work in a way that I have a hard time following. I honestly have no idea how the loop they made works. It works, and I use it now, but that's my mistake. I want to start fresh and get a return for each user in an array, then construct things out based on the results of their live status. I don't understand how it is currently being done with this code, and I can't seem to figure out the point where it is saving the return, so I can't properly log it to the console to look at it and use it proper.
Long story short, can anybody help me with a simple return in a loop for each user so I can log it to the console and look at it and use it DIRECTLY instead of saving pieces to a million variables? Here's the code I'm currently using:
$(document).ready(function () {
var casters = ["marcusraven86","whit3rabbit87","dragonbornmonocle","m3ta1head","jimmyjojo7","redshoes","sergeantatams","stevechopz"];
var castersLive = [];
var reqs = $.map(casters, function (userName, i) {
return $.getJSON('https://api.twitch.tv/kraken/streams/' + userName + '.json?callback=?');
})
$.when.apply($, reqs).done(function () {
$.each(arguments, function (i, array) {
var data = array[0];
var userName = casters[i];
console.log(data);
if (data.stream === null) {
$('<div class="streampost"></div>').append(
'<a id="offline' + userName + '" class = "offline" href="http://www.twitch.tv/' + userName + '/profile" title="' + userName + '" target="_blank"></a>').appendTo('#statusblock');
}
else {
castersLive.push(casters[i]);
$('<div class="streampost"></div>').append(
'<a id="online' + userName + '" class = "online" href="http://player.twitch.tv/?channel=' + userName + '" title="' + userName + '" target="stream"></a>').appendTo('#statusblock');
}
});
console.log(castersLive);
if (castersLive.length > 0) {
$('<div class="streamplayer embed-responsive embed-responsive-16by9"></div>').append('<iframe src="http://player.twitch.tv/?channel=' + castersLive[0] +'" name="stream"></iframe><iframe src="http://www.twitch.tv/' + castersLive[0] + '/chat?popout=" frameborder="0" scrolling="no" height="478" width="350" id="chatFrame" name="chatFrame"></iframe>').appendTo('#streamblock');
}
else {}
$('.online').click(function() {
var streamName = $(this).attr('title');
$('#chatFrame').attr('src', 'http://www.twitch.tv/' + streamName + '/chat?popout=');
});
});
});
And here is where I'm trying to restart, but I can't seem to get the call to the API correct. I'm still a bit new to all this, and I also use the Tumblr and YouTube APIs. Each is different, and it throws me off a little.
$(document).ready(function () {
var casters = ["marcusraven86","whit3rabbit87","dragonbornmonocle","m3ta1head","jimmyjojo7","redshoes","sergeantatams","stevechopz"];
var castersLive = [];
for (i=0; i <= casters.length; i++) {
$.get('https://api.twitch.tv/kraken/streams/' + casters[i] + '.json?callback=?'), function ( data ) {
console.log(data);
};
};

Google Maps: Find all zip codes along route

Given two locations you can calculate a route in Google Maps.
Is it possible to find all zip codes along the route?
Given a zip code, can I expand the area easily with a 10 km radius and find all zip codes in that area?
What methods should I use to get this information? Tutorials are welcome. I don't need a complete working solution, although if one is available that would be really nice.
You need a data source containing the zipcode (ZCTA) polygons. One possible source is this FusionTable.
proof of concept
proof of concept showing ZCTA polygons
Note: since it queries for the zip code at every point along the route, it will take longer to finish the longer the route is.
code that performs the query (using the Google Visualization API):
function queryForZip(latlng) {
//set the query using the current latlng
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, CIRCLE(LATLNG"+latlng+",1))";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(addZipCode);
}
function addZipCode(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
document.getElementById('status').innerHTML += 'Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()+"<br>";
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
for(i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
if (!zipcodes[zipStr]) {
zipcodes[zipStr] = zipStr;
document.getElementById('zipcodes').innerHTML += zipStr+"<br>";
}
}
}

Update jqGrid table with the results of Fusion Tables query in a Google Maps v3 page

I am looking to understand how to update a jqGrid table from Fusion Tables (FT) -
at the moment I can search or scroll on a Google Map, send an event listener that compiles a FT query of the spatial bounds of the viewport/map, to get a new set of results.
I want to use the new FT query string (or could use the Google code to retrieve the data - query.send(getData);) to update the jqGrid table with the new values.
Before I started using jqGrid, I tried/suceeded with the Google Visualisation API, and some of that code is below. Could anyone suggest how to move from table.draw, to loading/reloading a jqGrid table? Thanks a lot in advance.
function tilesLoaded() {
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', getSpatialQuery);
google.maps.event.addListener(map, 'dragend', getSpatialQuery);
getSpatialQuery();
}
function getSpatialQuery() {
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var spatialQuery = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
changeDataTable(spatialQuery);
}
function changeDataTable(spatialQuery) {
var whereClause = "";
if(spatialQuery) {
whereClause = " WHERE " + spatialQuery;
}
var queryText = encodeURIComponent("SELECT 'latitude', 'longitude', 'name' FROM xxxxxxxx" + whereClause + " LIMIT 50");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
query.send(getData);
}
function getData(response) {
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {showRowNumber: true});
}
Oh, and I used Oleg's code jqGrid returns blank cells as a basis for just seeing if I could get a simple multi-select table to pull data from my FT - that worked fine with the simple mod of
url: 'http://www.google.com/fusiontables/api/query?sql=' +
In case this helps someone, I've taken some of the code I came up with and pasted it below:
// You can get the map bounds via then pass it via a function (below is hacked from several functions
sw = map.getBounds().getSouthWest();
ne = map.getBounds().getNorthEast();
var whereClause = "ST_INTERSECTS(latitude, RECTANGLE(LATLNG(" + sw.lat() + "," + sw.lng() + "), LATLNG(" + ne.lat() + "," + ne.lng() + ")))";
//construct the URL to get the JSON
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; //
var queryOrderBy = ' ORDER BY \'name\' ASC';
var queryMain = "SELECT * FROM " + tableid + whereClause + queryOrderBy + " LIMIT 100";
var queryurl = encodeURI(queryUrlHead + queryMain + queryUrlTail);
//use the constructed URL to update the jqGrid table - this is the part that I didn't know in my above question
$("#gridTable").setGridParam({url:queryurl});
$("#gridTable").jqGrid('setGridParam',{datatype:'jsonp'}).trigger('reloadGrid');