I am developing an API mashup in Ruby on Rails and trying to fetch tweets from twitter based on hash tags. After fetching I am trying to display them on google maps. I am using Gmaps4rails, Geocoder, Twitter gems for this. For Identification of the user's location I am using the location field in the tweets and geocoding them.
The problem is that I am not getting the coordinates. Till now I am able to fetch the tweets based on hash tags and their location. When I am trying to Geocode the location and creating the coordinates in an array I am getting a nil class exception.
Code for Searching Hashtag
def search(hashtag)
client = Twitter::REST::Client.new do |config|
config.consumer_key = Rails.application.config.twitter_key
config.consumer_secret = Rails.application.config.twitter_secret
config.access_token = oauth_token
config.access_token_secret = oauth_secret
end
geoloc="53.349740,-6.256845,500mi"
tweets = client.search(hashtag,{:geocode => geoloc ,:lang => "en" , :count => 15})
return tweets
end
For Geocoding I have tried these variation in controller
def search
@tweets=current_user.search(tweet_params[:hashtag])
@tweets.each do |tweet|
@tweet["latlang"] = Geocoder.search(tweet.user.location).coordinates
end
end
def search
@tweets=current_user.search(tweet_params[:hashtag])
@tweets.each do |tweet|
@loc<<
{
:lat => Geocoder.search(tweet.user.location.to_s).first.coordinates.first,
:lng => Geocoder.search(tweet.user.location.to_s).first.coordinates.last
}
end
end
def search
@tweets=current_user.search(tweet_params[:hashtag])
@tweets.each do |tweet|
if(tweet.user.location.present?)
@loc<<
{
:lat => Geocoder.search(tweet.user.location.to_s).first.coordinates.first,
:lng => Geocoder.search(tweet.user.location.to_s).first.coordinates.last
}
else
continue
end
end
end
or I could create a new array in which I can push all the values
@location<<
{
:latlng => Geocoder.search(tweet.user.location).coordinates
}
I am getting error like "undefined method `<<' for nil:NilClass"
Thanks
I have figured out the solution with great help from Syed Aslam
The problem of getting NilClass exception was generic because I have not defined the array before using it.
Controller Code
def search
@tweets=current_user.search(tweet_params[:hashtag])
@loc=[]
@tweets.each do |tweet|
if(tweet.user.location.present?)
@loc<<
{
:lat => Geocoder.search(tweet.user.location.to_s).first.coordinates.first,
:lng => Geocoder.search(tweet.user.location.to_s).first.coordinates.last
}
else
end
end
end
View Code
<h2><%= @loc.to_json %></h2>
Script to Add markers
</div>
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw @loc.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
</script>