After the user clicks to save their position, we will store it in our longitude and latitude columns. Thank you for helping us with this task!
Visit our Github repository here.
Below is the excerpt from our HTML file where users can save their location coordinates:
<h1>Users#edit for <%= @user.id %></h1>
<p>You can find me in app/views/users/edit.html.erb</p>
<p><button onclick="geoFindMe()" data-id="<%= @user.id %>"id="finder-btn">Geo-Coordinate My Position</button>Send Coordinates to Database</p>
<div id="out"></div>
<h2>Coordinates to DataBase!</br>lat, lon</h2>
<a href="#" onclick="this.style.backgroundColor='#990000'">Paint it red</a>
Here is the JavaScript file used for handling the button click event:
$(function(){
$('#finder-btn').on('click', function (){
var currentUserId = $(this).attr('data-id')
$.ajax({
url: '/users/' + currentUserId,
data: { latitude: LatLng[0], longitude: LatLng[1] },
type: 'get',
success: function(data) {
console.log("Location successfully updated!")
},
error: function(err) {
console.log("Error updating location")
}
});
});
});
//update location for current_user
LatLng = [];
console.log(LatLng);
var latitude = LatLng[0]
var longitude = LatLng[1]
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
// console.log(longitude);
// console.log(latitude);
//PLUCK into Location TABLE
// latitude = lat_Jon;
// longitude = lon_Jon;
LatLng.push(latitude);
LatLng.push(longitude);
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
We also need to update the location details in our users_controller for latitude and longitude:
def update
# @user = User.find(session[:user_id])
user_id = current_user.id
@user = User.find(user_id)
@user.update_attributes(user_params)
puts @user.latitude
end