Reputation: 105
I have a simple JavaScript code that gets the users coords, works fine in computers but can't say the same for mobiles.
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
got this from w3schools. first time it asked if i wanted to share my location(agreed) and when i press the button to execute the function nothing happens(no error message too), works on my pc so it's not the code. tried on 2 different devices:galaxy nexus and galaxy s2 both jellybeaned. tried on chrome, chrome beta, firefox and the built in broweser. on some of them it doesn't even bother to pop the "share location" message. how do I fix this?
Upvotes: 1
Views: 1352
Reputation: 12934
Html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://www.geoip-db.com They provide a JSON and JSONP-callback solution.
A plain javascript example:
<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geoip-db.com</title>
</head>
<body>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Postal: <span id="postal"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP address: <span id="ipv4"></span></div>
</body>
<script>
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = document.getElementById('city');
var postal = document.getElementById('postal');
var latitude = document.getElementById('latitude');
var longitude = document.getElementById('longitude');
var ip = document.getElementById('ipv4');
function callback(data)
{
country.innerHTML = data.country_name;
state.innerHTML = data.state;
city.innerHTML = data.city;
postal.innerHTML = data.postal;
latitude.innerHTML = data.latitude;
longitude.innerHTML = data.longitude;
ip.innerHTML = data.IPv4;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://geoip-db.com/json/geoip.php?jsonp=callback';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(script, h);
</script>
</html>
Upvotes: 0
Reputation: 1489
I've had this issue before, and I believe that it isn't possible to force share location on, you at least have to prompt the user as to whether they want to turn location services on. However, here's a thread which details how you can prompt an android user to turn on share location. Also, I would avoid using w3schools.
Good geolocation app: http://www.9lessons.info/2011/06/geo-location-with-html5-and-jquery.html
Upvotes: 1