forked from paulirish/Twitter-Friends-Map
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwitterFriends.js
393 lines (356 loc) · 13 KB
/
TwitterFriends.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
* Create the initial map on map load from Google Map
* Depends on Google Maps, an Element with id="map_canvas"
*
*/
var map = (function(){
var latlng = new google.maps.LatLng(39, -94),
options = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById("map_canvas"), options);
})();
/*
* Base Constructor for the TwitterFriends Object
* Currently depends on jQuery and Underscore for initial convenience
* Depends on jQuery for AJAX compatibility, and Underscore for _.isEqual
*
*/
var TwitterFriends = function(sn, ls){
this.follows = ls ? JSON.parse(localStorage.getItem('follows')) || [] : [];
this.locations = ls ? JSON.parse(localStorage.getItem('locations')) || [] : [];
this.calledLocations = 0;
this.markers = [];
this.receivedLocations = 0;
this.receivedCalls = 0;
this.totalCalls = 0;
this.map = map;
this.callTimeout = 0;
this.getTwitterFriendIds(sn);
};
TwitterFriends.prototype.constructor = TwitterFriends;
/*
* Get your followers ids from the twitter API and send them
* to the twitterFriends.receiveFollowerIds callback
* depends on having a global instance of TwitterFriends named twitterFriends
*
*/
TwitterFriends.prototype.getTwitterFriendIds = function(sn){
//if we have data stored in localStorage use it
if(this.follows.length){
if(this.locations.length){
this.refreshLatLng();
this.groupByLocation();
} else {
this.sendGeoCalls();
}
} else {
var url = 'https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name='+sn+'&callback=twitterFriends.receiveFollowerIds';
$.ajax({url:url, dataType:'jsonp', statusCode: {400: function(){$('.twitter-alert').show();}}});
}
};
/*
* Create an array of arrays, each holding 100 ids of followers
* this breaks up the requests to we don't have one giant request
* and send the requests to createUserCallString to be assembled
*
*/
TwitterFriends.prototype.receiveFollowerIds = function(data){
var chunkedFriends = [], tmpArr = [];
this.setFollowersMessage(data.ids.length);
for(var i = 0, l = data.ids.length; i < l; i++){
tmpArr.push(data.ids[i]);
if(tmpArr.length === 100){
chunkedFriends.push(tmpArr);
tmpArr = [];
}
}
chunkedFriends.push(tmpArr);
this.createUserCallString(chunkedFriends);
};
/*
* Set followers message to update the user on approximate time left
*
*/
TwitterFriends.prototype.setFollowersMessage = function(f){
var n = f ? f : this.follows.length;
$('.followers').show().html($('.sn-input').val()+' is following '+n+' people.');
};
/*
* Assemble strings to make AJAX calls against the Twitter API
* returns Twitter User data to the receiveCallStringResults callback
* Only work if we are not using LocalStorage
*
*/
TwitterFriends.prototype.createUserCallString = function(users){
//create an array of strings to make separate calls the the twitter JSON API
var callStrings = [],
str = 'https://api.twitter.com/1/users/lookup.json?user_id=',
tmpStr = str;
for(var i = 0, l = users.length; i < l; i++){
for(var j = 0, k = users[i].length; j < k; j++){
tmpStr += users[i][j] + ',';
}
tmpStr = tmpStr.substring(0, tmpStr.length - 1);
tmpStr += '&callback=twitterFriends.receiveCallStringResults';
callStrings.push(tmpStr);
tmpStr = str;
}
//save the total number of call we make the the Twitter API for later use
this.totalCalls = callStrings.length;
this.sendCallStrings(callStrings);
};
/*
* Make the AJAX calls
* returns Twitter User data to the receiveCallStringResults callback
*
*/
TwitterFriends.prototype.sendCallStrings = function(callStrings){
for(var i = 0; i < callStrings.length; i++){
$.ajax({url:callStrings[i], dataType:'jsonp'});
}
};
/*
* Push all of the User data returned from Twitter into the follows array
*
*/
TwitterFriends.prototype.receiveCallStringResults = function(data){
//increment for the number of results we have received
this.receivedCalls++;
//push the user data into the follows array
for(var i = 0, l = data.length; i < l; i++){
this.follows.push(data[i]);
}
//when we know we have all the data get Geo data for each follower
if(this.receivedCalls == this.totalCalls){
this.sendGeoCalls();
}
};
/*
* Utility function for calling the geoCoder and saving the index
* this should be refactored or renamed at the least
*
*/
TwitterFriends.prototype.sendGeoCalls = function(){
for(var i = 0, l = this.follows.length; i < l; i++){
this.callGeoCoder(this.follows[i].location, i);
}
};
/*
* Create the call AJAX call strings for the Yahoo! Places API
*
*/
TwitterFriends.prototype.callGeoCoder = function(location, index){
if(location){
//remove whitespace and replace with plusses
location = location.replace(/\s/g, '+');
var url = 'http://where.yahooapis.com/geocode?location='+location+'&flags=J&appid=dj0yJmk9WGUydmhyQ0RtekIxJmQ9WVdrOWRVVlpaMmhvTkdjbWNHbzlNVFUyTnpNeU5ERTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD01ZA--&callback=receiveGeoCall';
this.callGetJson(url, location, index);
}
};
/*
* Finally make calls to the Yahoo! Places API
* callback sends the Latatitude and Longitude to handleLocations
*
*/
TwitterFriends.prototype.callGetJson = function(url, location, index){
this.calledLocations++;
var that = this;
$.ajax({
url: url,
error: function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus + " errorThrown" + errorThrown);
console.log("incoming Text " + jqXHR.responseText);
},
success: function(response){
var i = index, result;
response = (typeof response == 'string') ? JSON.parse(response) : response;
that.receivedLocations++;
if(!response.ResultSet){
response = that.xmlToJson(response);
}
if(response.ResultSet.Found >= 1){
result = response.ResultSet.Results[0];
} else {
return;
}
var person = that.follows[i];
var LatLng = new google.maps.LatLng(result.latitude, result.longitude);
//handle the location information for each person
that.handleMarkerGroups(LatLng, person);
}
});
};
/*
* Implemented this xmlToJson function, just copy-pasted
* from David Walsh's blog, this is used to fix Yahoo! sending
* XML even when I request JSON
*
*/
TwitterFriends.prototype.xmlToJson = function(xml){
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = this.xmlToJson(item);
} else {
if (typeof(obj[nodeName].length) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.xmlToJson(item));
}
}
}
return obj;
};
/*
* If we are using localStorage we lose inheritance of
* google maps objects. And they need to be recreated.
*
*/
TwitterFriends.prototype.refreshLatLng = function(){
var ll;
for(var i = 0, l = this.locations.length; i < l; i++){
ll = this.locations[i].latLng;
ll = new google.maps.LatLng(ll.Na, ll.Oa);
this.locations[i].latLng = ll;
}
};
TwitterFriends.prototype.handleMarkerGroups = function(LatLng, person){
//each person has a unique location until we check that they don't
var uniqueLocation = true;
for(var i = 0, l = this.locations.length; i < l; i++){
//check if the location coming back is equal to any of the locations we have
if(_.isEqual(LatLng, this.locations[i].latLng)){
//if the location is equal push the person into the existing object
this.locations[i].followers.push(person);
//recalculate necessary markup and refresh the marker
this.resetMarkupAndRefresh(this.locations[i]);
return;
}
}
//create single person markup
var markup = '<div class="single-marker">';
markup += '<div style="height:60px;width:60px;border-radius:60px;overflow:hidden;" class="img-container"><img src="'+person.profile_image_url+'"/></div>';
markup += '</div>';
var marker = new RichMarker({
position: LatLng,
map: map,
shadow: '',
content: markup
});
this.markers.push(marker);
var locationObject = {
latLng : LatLng,
followers : [person],
marker : marker
};
this.locations.push(locationObject);
};
/*
* Much cleaner way to dynamically add users to the map
*
*/
TwitterFriends.prototype.resetMarkupAndRefresh = function(locationObj){
var marker = locationObj.marker,
fol = locationObj.followers.length,
width = Math.ceil(fol/10) * 7,
points = this.circlePoints(120, fol, 0, 0),
top, left, person,
markup = '<div class="group-marker">'+ '<div class="group-amount" style="margin-left:-'+width+'px;">'+fol+'</div><div class="group-img-wrap">';
for(var i = 0, l = locationObj.followers.length; i < l; i++){
person = locationObj.followers[i];
top = points[i][0];
left = points[i][1];
markup += '<div style="position:absolute;top:'+top+'px;left:'+left+'px;height:60px;width:60px;border-radius:60px;overflow:hidden;" class="img-container"><img src="'+person.profile_image_url+'"/></div>';
}
markup += '</div></div>';
marker.content = markup;
marker.setMap(map);
};
TwitterFriends.prototype.followsLeft = function(){
var followsLeft = (this.calledLocations - this.receivedLocations);
var text = followsLeft ? 'Waiting for information for '+followsLeft+' more people.' : 'Check out your people';
$('.followers-received').show().html(text);
return followsLeft;
};
/*
* Utility function for returning circular points about a center
*
*/
TwitterFriends.prototype.circlePoints = function(radius, steps, centerX, centerY){
var xValues = [], yValues = [], points = [], tmpX, tmpY;
for (var i = 0; i < steps; i++) {
xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
tmpX = Math.floor(xValues[i]);
yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));
tmpY = Math.floor(yValues[i]);
points.push([tmpX, tmpY]);
}
return points;
};
/*
* Refactor this jumbled mess, possibly use Handlebars.js for templating
* This function works well if we have all the data, but we need to work
* dynamically and add users to groups when we get them.
*
*/
TwitterFriends.prototype.groupByLocation = function(){
var LatLng, markup, person, points, top, left;
console.log('I made it');
for(var i = 0, l = this.locations.length; i < l; i++){
var fol = this.locations[i].followers.length;
//let's be really anal about text positioning shall we
var width = Math.ceil(fol/10) * 7;
markup = '<div class="group-marker">'+ '<div class="group-amount" style="margin-left:-'+width+'px;">'+fol+'</div><div class="group-img-wrap">';
LatLng = this.locations[i].latLng;
for(var j = 0, k = this.locations[i].followers.length; j < k; j++){
person = this.locations[i].followers[j];
if(j === 0 && k == 1){
top = 0;
left = 0;
markup = '<div class="single-marker">';
} else {
points = this.circlePoints(120, k, 0, 0);
top = points[j][0];
left = points[j][1];
}
markup += '<div style="position:absolute;top:'+top+'px;left:'+left+'px;height:60px;width:60px;border-radius:60px;overflow:hidden;" class="img-container"><img src="'+person.profile_image_url+'"/></div>';
}
markup += '</div></div>';
marker = new RichMarker({
position: LatLng,
map: map,
shadow: '',
content: markup
});
this.markers.push(marker);
}
var followsString = JSON.stringify(this.follows);
localStorage.setItem('follows', followsString);
this.cleanup();
};
TwitterFriends.prototype.cleanup = function(){
this.setFollowersMessage();
this.followsLeft();
};