I've got an application that uses node/express/socket.io to mark tweets on a map. I'm also trying to include some sentiment analysis, so I'm using npm sentiment like this:
var sentiment = require('sentiment');
twit.stream('statuses/filter', { locations: locs }, function(stream) {
stream.on('data', function (data) {
var geo=false,latitude,longitude;
if(data.geo!=null){
// calculate sentiment
var tweetSentiment, sentimentRadius, sentimentColor;
sentiment(data.text, function (err, result) {
tweetSentiment = result;
if (result == 0) {
sentimentRadius = 300;
} else if (result >=0) {
sentimentRadius = result*100;
sentimentColor = '#FC0828';
} else {
sentimentRadius = (0-result)*100;
sentimentColor = '#00DE1E';
}
io.sockets.volatile.emit('tweets', {
user: data.user.screen_name,
text: data.text,
geo : geo,
latitude: latitude,
longitude: longitude,
sentimentRadius: sentimentRadius,
sentimentColor: sentimentColor
});
});
geo = true;
latitude = data.geo.coordinates[0];
longitude = data.geo.coordinates[1];
}
});
});
And in socket.js (called from the browser):
// Add a marker to the map
var tweetMarker = new google.maps.Circle({
center:new google.maps.LatLng(data.latitude, data.longitude),
radius:data.sentimentRadius,
strokeColor:data.sentimentColor,
strokeOpacity:0.7,
strokeWeight:1,
fillColor:data.sentimentColor,
fillOpacity:0.7
});
tweetMarker.setMap(map);
But I get the error in the browser console that:
Uncaught ReferenceError: sentimentRadius is not defined
So it seems that this variable is not being emitted. Any pointers as to what I'm doing wrong?
Two things:
sentiment function is async so the emit could be called before
sentiment finishes. Call emit in the callback instead.sentimentRadius is not defined. You must use data.sentimentRadius instead (data is the object the server sends to the client). Same thing for sentimentColor.[From OP update]
You set your lat/long after you emit, they will be undefined.
I assume that you wrap var tweetMarker = ... into the socket.on function right?