I am trying to get user's city using geokit and Google Geocoder. I am getting the user's city from an ajax request:
var geocoder;
var map;
function initialize(position) {
geocoder = new google.maps.Geocoder();
var lat = position.coords.latitude;
var long = position.coords.longitude;
getCitizenCity(lat, long);
}
function getCitizenCity(lat, long) {
$.ajax({
type: "POST",
url: "/set_citizen_city",
dataType: 'json',
data: { lat: lat, long: long },
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(initialize);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
google.maps.event.addDomListener(window, 'load', getLocation);
The rails code (HomeController.rb):
class HomeController < ApplicationController
attr_reader :citizen_city
def index
end
def set_citizen_city
lat = params[:lat]
long = params[:long]
address = Geokit::Geocoders::GoogleGeocoder.reverse_geocode("#{lat}, #{long}")
@citizen_city = address.city
respond_to do |format|
format.json { render :json => {:message => "Success"} }
end
end
end
I have noticed that if I do
puts @citizen_city
inside the method "set_citizen_city", the correct city is shown in the console. But, if I try
puts @citizen_city
inside the method "index", nothing is displayed in the console.
What do I have to do to display the city's name on the console?
I think you can't see@citizen_city
in index is because it is not defined there.
On every request Rails does a new instance of the application(as far as I know) so controller instance variables can't be accessed if they are not defined in the same action. To fix this I suggest you save the lat
and long
params in the database and then in index just do the same thing you do in set_citizen_city
when defining @citizen_city
only then look up coordinates from the database(or possibly session params, if that's what you need)