ahuang7
ahuang7

Reputation: 2190

Mobile geolocation with Rails?

Currently I'm using Ruby Geocoder and Sunspot for geolocated search. It works for desktop browsers because the IP address has specific coordinates. However for mobile browsers it does not work unless the device is connected to wifi, what's the best way to get latitude and longitude coordinates for mobile devices? I'd preferably like to have one solution for both desktop and mobile. Thank you!

Upvotes: 1

Views: 1764

Answers (1)

rorra
rorra

Reputation: 9693

You can use HTML 5 Geolocation, it won't work for old browsers, but for those browsers that doesn't support Geolocation, you can still use the IP Geolocation as a backup.

 if (navigator.geolocation) {
   var timeoutVal = 10 * 1000 * 1000;
   navigator.geolocation.getCurrentPosition(
     displayPosition, 
     displayError,
     { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
   );
 } else {
   alert("Geolocation is not supported by this browser");
 }

 function displayPosition(position) {
   alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
 }

 function displayError(error) {
   var errors = { 
     1: 'Permission denied',
     2: 'Position unavailable',
     3: 'Request timeout'
   };
   alert("Error: " + errors[error.code]);
 }

Not sure what you are doing, but by js you can try to store the user location and latitude in a hidden variable, and when he submits, if you receive the latitude and longitude, you store it, otherwise, you check the remote ip and do geolocalization by ip (so geolocalization by ip its just a backup).

Upvotes: 4

Related Questions