Reputation: 382
So I'm developing an web application using Ruby on Rails, and I want to find a way where the user, upon creating his account, may set his location. I was thinking about something like a google maps API for rails, where the user would select his place of living.
If anyone have any tips on that I'll be thankful!
Upvotes: 1
Views: 696
Reputation: 7146
There is a good SlideShare that talks about enabling geolocation in your rails app. You can easily get the location of a user and set it up as their default using javascript.
Lets say you want to get the current location of a user and display it in your views: First include the appropriate google maps api js library:
<script src="https://maps.googleapis.com/maps/api/js"></script>
views/index
<body>
<div class="container">
<div class="error-message">
</div>
<div class="jumbotron">
<h1>Google Maps</h1>
</div>
<div class="location">
<div class="loc longitude">
<h3>Longitude</h3>
<p id="longitude"><i class="fa fa-spinner fa-spin"></i></p>
</div>
<div class="loc latitude">
<h3>Latitude</h3>
<p id="latitude"><i class="fa fa-spinner fa-spin"></i></p>
</div>
</div>
<div class="row">
<div class="col-md-12 google-map-container">
<div id="google-map">
<h3>Map</h3>
<div id="map_canvas">
<div class=" ">
<i class="fa fa-spinner fa-spin fa-5x"></i>
</div>
</div>
</div>
</div>
</div>
</div> <!-- /container -->
</html>
Now lets say you have two js files, one that fetches the user longitude and latitude and another that created and inserts a map based on the users location
fetch_location.js
$(document).ready(function(){
var x = document.getElementById("latitude");
var y = document.getElementById("longitude");
// $('.vertical-align').hide();
function getLocation() {
navigator.geolocation.getCurrentPosition(function(position){
x.innerHTML = position.coords.latitude.toFixed(4);
y.innerHTML = position.coords.longitude.toFixed(4);
insertMap(latitude,longitude);
});
}
getLocation();
});
Then in inser_map.js
function insertMap(latitude, longitude) {
$('#map_canvas').html(initialize(latitude,longitude));
function initialize(latitude,longitude){
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(latitude,longitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
google.maps.event.addDomListener(window, 'load', initialize);
}
}
The insertMap function will populate the div of id map_canvas
with the map and a pin of the location of the user.
You can then use this information to persist the user's location to the db.
Upvotes: 1