mapping with twitter APIs

How To Use The New Twitter API

About

@Tweereal is the map of twitter users activity in real-time. Animation on the map include only tweets containing geo-tags. There are two types of tweets on a map: with the exact coordinates and the coordinates determined with an accuracy of 1 degree (more transparent). Based on Twitter Streaming API and Google Maps Javascript API.

For live testing: be sure that your “test tweet” contains geotag (coordinates). Even with coordinates your tweet could be rate limited by Twitter API (see “Twitter API flow quality” field and try to tweet several times) or dropped by our filter as tweet with low precision.

http://tweereal.com/

http://www.codecademy.com/zh/courses/ruby-intermediate-en-rUwFe/0/1?curriculum_id=5122d5f811fbdb5456005922

 

 

In today’s tutorial we will create an interactive Google map using the geocoding service. Using the Twitter API we will retrieve the user’s location, and then display the profile picture on the map. We will also add the click action, after which we will retrieve the user’s 5 latest tweets.

THE MARKUP

At the beginning let’s write some simple HTML code.

<div id="map"></div>
<div class="twitter">
    <div class="inside"></div>
</div>
<div class="posts"></div>
<div class="get">
    <input type="hidden" value="marcinmobily" />
    <input type="hidden" value="codrops" />
    <input type="hidden" value="onextrapixel" /> 
    <input type="hidden" value="smashingmag" />          
    <input type="hidden" value="umutm" />
    <input type="hidden" value="1stwebdesigner" />   
    <input type="hidden" value="chriscoyier" />  
    <input type="hidden" value="marcofolio" />           
</div>   

Let’s examine the code line-by-line. The first “div” will display a Google map. Another “div” is the place where we store the description, name and profile picture of the Twitter users. Next, we create a “div” which will display the last 5 tweets.

At the end of the block, we store the Twitter user name, which will be used to download the location. If this is already done, we can proceed to write the JavaScript code.

THE JAVASCRIPT

At the beginning we should define the global variables.

1
var map, geocoder, marker, ey, my, mouseDown = false;

Then we create the main object that will incorporate all functions used by us. The most important function in this object is the ‘init’ function.

1
2
3
4
5
6
7
var map, geocoder, marker, ey, my, mouseDown = false;
var o = {
    init: function(){
        // in this place we will call all needed functions
    }
}
$(function(){ o.init(); }  

Let’s create a new object called “map” in the main “o” object. It is an object, where the function initiating a Google Map will be placed. The first function in this object is the “size” function, where we draw the current window size. This is what we need in order to display the map in full screen. Then we create the object entitled “data” with the parameters: “zoom”, “center” and “mapTypeId”. When the DOM is ready we call the init function.

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
var map, geocoder, marker, ey, my, mouseDown = false;
var o = {
    init: function(){
        this.map.init();
    },
    map: {
        size: function(){
            var w = $(window).width(),
                h = $(window).height();
            return { width: w, height: h }
        },
        data: {
            zoom: 3,
            center: new google.maps.LatLng(52, 23),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        init: function(){
            var size = o.map.size();
            $('#map').css({ width: size.width, height: size.height });
            map = new google.maps.Map(document.getElementById('map'), o.map.data),
            geocoder = new google.maps.Geocoder();
            google.maps.event.addListener(map, 'dragstart', function(){
                $('.posts').hide();
            });
        }
    }
}
$(function(){ o.init(); }  

The next step is to create an object, where we will retrieve the Twitter user data such as name, description, location and the path to the profile picture. First, we create a function where we will retrieve the value of the ‘input’ fields and we will store it in the array. The next stage is another function where every element of previously created tables is looped. Thus, by using the Twitter API, we can extract the user’s location and using a geocoding service we can convert it to geographic coordinates. At the end, we show the user in the right place on the map and put the name, description and user picture to a blank ‘div’ just called ‘twitter’ 😉

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
var map, geocoder, marker, ey, my, mouseDown = false;
var o = {
    init: function(){
        this.map.init();
        this.twitter.show();
        this.twitter.click();
    },
    twitter: {
        get: function(){
            var arr = new Array;
            $('.get').find('input').each(function(i){
                var t = $(this),
                    val = t.val();
                arr[i] = val;              
            });
            return arr;
        },
        show: function(){
            var users = o.twitter.get(),
                arr = new Array;
            for (i in users){
                var user = users[i];
                $.getJSON('http://twitter.com/users/show/'+user+'.json?callback=?', function(data) {
                    var img = data.profile_image_url,
                        screen_name = data.screen_name;
                    geocoder.geocode({ address: data.location }, function(response, status){
                        if (status == google.maps.GeocoderStatus.OK) {
                            var x = response[0].geometry.location.lat(),
                                y = response[0].geometry.location.lng();
                            marker = new google.maps.Marker({
                                icon: img,
                                map: map,
                                title: screen_name,
                                position: new google.maps.LatLng(x, y)
                            });
                            arr.push('<div>');
                            arr.push('<p><a href="#" rel="'+screen_name+'"><img src="'+img+'" alt="" /></a></p>');
                            arr.push('<div>');
                            arr.push('<a href="#" rel="'+screen_name+'">'+data.name+'</a>');
                            arr.push('<p>'+data.description+'</p>');
                            arr.push('<p><a href="'+data.url+'" target="_blank">'+data.url+'</a></p>');
                            arr.push('<p>Followers: '+data.followers_count+', Following: '+data.friends_count+'</p>');
                            arr.push('</div>');
                            arr.push('</div>');
                            var html = arr.join('');
                            arr = [];
                            $('.twitter').find('.inside').append(html);
                            google.maps.event.addListener(marker, 'click', function(){
                                o.twitter.open(this.title);
                            });
                        }
                    });
                });
            }
        },
        click: function(){
            $('.twitter').find('.open').live('click', function(){
                var t = $(this), rel = t.attr('rel');
                o.twitter.open(rel);
            });
        },
        open: function(user){
            var posts = $('.posts'), arr = new Array;
            $.getJSON('http://twitter.com/status/user_timeline/'+user+'.json?count=5&callback=?', function(data) {
                $.each(data, function(i, post){
                    arr.push('<div>');
                    arr.push(post.text);
                    arr.push('</div>');
                });
                var html = arr.join('');
                posts.html(html).fadeIn();
            });
        }
    },
    map: {
        size: function(){
            var w = $(window).width(),
                h = $(window).height();
            return { width: w, height: h }
        },
        data: {
            zoom: 3,
            center: new google.maps.LatLng(52, 23),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        init: function(){
            var size = o.map.size();
            $('#map').css({ width: size.width, height: size.height });
            map = new google.maps.Map(document.getElementById('map'), o.map.data),
            geocoder = new google.maps.Geocoder();
            google.maps.event.addListener(map, 'dragstart', function(){
                $('.posts').hide();
            });
        }
    }
}
$(function(){ o.init(); }  

Lastly, we will add a ‘scroll’ object that has a function called ‘init’ which is responsible for scrolling the ‘.twitter’ div vertically.

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
var map, geocoder, marker, ey, my, mouseDown = false;
var o = {
    init: function(){
        this.map.init();
        this.twitter.show();
        this.twitter.click();
    },
    twitter: {
        get: function(){
            var arr = new Array;
            $('.get').find('input').each(function(i){
                var t = $(this),
                    val = t.val();
                arr[i] = val;              
            });
            return arr;
        },
        show: function(){
            var users = o.twitter.get(), // retrieve all users which are stored in html
                arr = new Array;
            for (i in users){
                var user = users[i];
                $.getJSON('http://twitter.com/users/show/'+user+'.json?callback=?', function(data) {
                    var img = data.profile_image_url,
                        screen_name = data.screen_name;
                    geocoder.geocode({ address: data.location }, function(response, status){
                        if (status == google.maps.GeocoderStatus.OK) {
                            var x = response[0].geometry.location.lat(),
                                y = response[0].geometry.location.lng();
                            marker = new google.maps.Marker({
                                icon: img,
                                map: map,
                                title: screen_name,
                                position: new google.maps.LatLng(x, y)
                            });
                            arr.push('<div>');
                            arr.push('<p><a href="#" rel="'+screen_name+'"><img src="'+img+'" alt="" /></a></p>');
                            arr.push('<div>');
                            arr.push('<a href="#" rel="'+screen_name+'">'+data.name+'</a>');
                            arr.push('<p>'+data.description+'</p>');
                            arr.push('<p><a href="'+data.url+'" target="_blank">'+data.url+'</a></p>');
                            arr.push('<p>Followers: '+data.followers_count+', Following: '+data.friends_count+'</p>');
                            arr.push('</div>');
                            arr.push('</div>');
                            var html = arr.join('');
                            arr = [];
                            $('.twitter').find('.inside').append(html);
                            google.maps.event.addListener(marker, 'click', function(){
                                o.twitter.open(this.title);
                            });
                        }
                    });
                });
            }
        },
        click: function(){
            $('.twitter').find('.open').live('click', function(){
                var t = $(this), rel = t.attr('rel');
                o.twitter.open(rel);
            });
        },
        open: function(user){
            var posts = $('.posts'), arr = new Array;
            $.getJSON('http://twitter.com/status/user_timeline/'+user+'.json?count=5&callback=?', function(data) {
                $.each(data, function(i, post){
                    arr.push('<div>');
                    arr.push(post.text);
                    arr.push('</div>');
                });
                var html = arr.join('');
                posts.html(html).fadeIn();
            });
        }
    },
    map: {
        size: function(){
            var w = $(window).width(),
                h = $(window).height();
            return { width: w, height: h }
        },
        data: {
            zoom: 3,
            center: new google.maps.LatLng(52, 23),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        init: function(){
            var size = o.map.size();
            $('#map').css({ width: size.width, height: size.height });
            map = new google.maps.Map(document.getElementById('map'), o.map.data),
            geocoder = new google.maps.Geocoder();
            google.maps.event.addListener(map, 'dragstart', function(){
                $('.posts').hide();
            });
        }
    },
    scroll: {
        mouse: function(e){
            var y = e.pageY;
            return y;
        },
        check: function(y){
            var all = $('.twitter').height(),
                inside = $('.twitter').find('.inside').height();
            if (y < (all - inside)) {
                y = all - inside;
            } else if (y > 0) {
                y = 0;
            }
            return y;
        },
        update: function(e){
            var y = o.scroll.mouse(e),
                movey = y-my,
                top = ey+movey;
                check = o.scroll.check(top);
            $('.twitter').find('.inside').css({ top: check+'px' });
        },
        init: function(){
            $('.twitter').find('.inside').bind({
                mousedown: function(e){
                    e.preventDefault();
                    mouseDown = true;
                    var mouse = o.scroll.mouse(e);
                        my = mouse;
                    var element = $(this).position();
                        ey = element.top;
                    o.scroll.update(e);
                },
                mousemove: function(e){
                    if (mouseDown)
                        o.scroll.update(e);
                    return false;
                },
                mouseup: function(){
                    if (mouseDown)
                        mouseDown = false;
                    return false;
                },
                mouseleave: function(){
                    if (mouseDown)
                        mouseDown = false;
                    return false;
                }
            });
        }
    }
}
$(function(){ o.init(); }  

THE CSS

First, we will embed our reset.css that will reset all the basic styles, and we’ll define some main properties:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@import url("reset.css");
html, body {
    margin:0;
    padding:0;
}
body {
    font-family:Arial, Helvetica, sans-serif;
    font-size:12px;
    color:#333;
    line-height:18px;
}
a {
    text-decoration:none;
    color:#fff;
}

Next, we will define the styles for the map, Twitter posts and descriptions.

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
.twitter {
    position:fixed;
    left:0;
    bottom:0;
    background:#000;
    background:rgba(0, 0, 0, .7);
    width:100%;
    height:180px;
    color:#fff;
    overflow:hidden;
}
.twitter .inside {
    position:absolute;
    top:0;
    left:0;
    cursor:n-resize;
}
.twitter .item {
    float:left;
    width:280px;
    padding:20px;
}
.twitter .item .img {
    float:left;
    width:48px;
}
.twitter .img img {
    -moz-box-shadow:0 0 5px #000;
    -webkit-box-shadow:0 0 5px #000;
    box-shadow:0 0 5px #000;
}
.twitter .item .entry {
    float:right;
    width:215px;
    height:140px;
    color:#eee;
    font-size:11px;
    position:relative;
}
.twitter .item .count {
    position:absolute;
    left:0;
    bottom:-10px;
    font-size:10px;
    text-transform:uppercase;
}
.twitter .item .title {
    font-size:13px;
    font-weight:bold;
    color:#fff;
}
.twitter .item .url a {
    text-decoration:underline;
}
.twitter .item p {
    margin-bottom:5px;
}
.posts {
    display:none;
    position:absolute;
    left:50%;
    margin-left:-310px;
    width:580px;
    bottom:180px;
    background:#fff;
    color:#fff;
    background:#000;
    background:rgba(0, 0, 0, .7);
    padding:20px;
}
.posts .post {
    float:left;
    clear:both;
    width:100%;
    margin-bottom:20px;
    font-size:12px;
    font-weight:bold;
}

CONCLUSION

In today’s tutorial you learned how to use a geocoding service and how to use the Twitter API. An important fact to remember is that Google has imposed some limits to its geocoding service. Maximum number of requests in one day from a single IP address is 2500. Also, Twitter will rate limit the IP address from which the request was made.

http://tympanus.net/Tutorials/InteractiveGoogleMapTwitter/

 

Advertisements