UPDATE: it doesn't work only on safari mobile (chrome for ios works correctly).
I am trying to get user location using google maps API.
It works correctly on desktop FF and Chrome (shows city and country) but it doesn't show anything on iOS safari (iOS 11). Also it seems that it doesn't work properly on some other mobile devices.
Note that I am using HTTPS so there are no problems with security.
Here's javascript code:
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
document.getElementById("userlocation").innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
lat=position.coords.latitude;
lon=position.coords.longitude;
displayLocation(lat,lon);
}
function showError(error){
switch(error.code){
case error.PERMISSION_DENIED:
document.getElementById("userlocation").innerHTML="User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
document.getElementById("userlocation").innerHTML="Location information is unavailable."
break;
case error.TIMEOUT:
document.getElementById("userlocation").innerHTML="The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
document.getElementById("userlocation").innerHTML="An unknown error occurred."
break;
}
}
function displayLocation(latitude,longitude){
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
document.getElementById("userlocation").innerHTML = city + ", " + country;
}
else {
document.getElementById("userlocation").innerHTML = "address not found";
}
}
else {
document.getElementById("userlocation").innerHTML = "Geocoder failed due to: " + status;
}
}
);
}
And here's HTML:
<body onload="getLocation()">
<p id="userlocation">Getting your location ...</p>
</body>
Thanks in advance.
In your mobile device, you have to enabled the geolocation for safari in the settings. If the geolocation is disabled, nothing will append.
Try this manipulation:
Go to settings.
Next, go to the confidentiality (with a hand in the left of the scroll menu).
Then, click to the location service bar.
Scroll down and accept the location's service for safari.
Tell me if you have some questions
Related
I have implemented the devise omniauth setup and when I’m signed in with either Facebook, twitter or google the html5 geolocation returns a position unavailable error. But when I'm logged in as regular devise user it works just fine! How can I allow access to the html5 geolocation on my rails app when logged in with a social media account?
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoCookie,showError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
window.location = window.location;
window.alert("Permission denied");
break;
case error.POSITION_UNAVAILABLE:
window.location = window.location;
window.alert("Location information is unavailable.");
break;
case error.TIMEOUT:
window.location = window.location;
window.alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
window.location = window.location;
window.alert("An unknown error occurred.");
break;
}
location.reload();
}
Update 1
I changed the code to the following and I'm getting the following errors inside the browser console:
Origin does not have permission to use Geolocation service
[blocked] Access to geolocation was blocked over secure connection with mixed content to https://localhost:3000.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geolocation is not supported by this browser.");
}
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
Any ideas on how to unblock this?
This is not a rails issue but a Javascript issue. Somewhere in your template, CSS, or Javascript you load something from http instead of https. Use your browser's inspector to find the culprit.
I am using the google geolocation's getCurrentPosition() function for get the current position of the user.
It works fine for me in firefox but not working on chrome.
My code is as below ::
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showtemp);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&key=AIzaSyDOgvRydLLNrztjgagobYS_sROK1u3r4M4&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
function showtemp(temp) {
alert("test");
}
function showError(error) {
$.get("http://ipinfo.io", function (response) {
var array = (response.loc).split(',');
console.log(array[0]);
var latlon = array[0] + "," + array[1];
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}, "jsonp");
}
</script>
</body>
</html>
Please help me solve this.
It Gives me error :: " getCurrentPosition() and watchPosition() are deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS."
Thanks in advance
getcurrentposition() is deprected and there is no replacement of it. read this answer :- getcurrentposition-and-watchposition-are-deprecated-on-insecure-origins
Click on this google updated api's example link it's working example. : https://developers.google.com/maps/documentation/javascript/examples/map-geolocation.
Hover at top right of the code block to copy the code or open it in JSFiddle.
Use this functions :
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
Geolocation is not deprecated per se, but limited to sites served via HTTPS.
The warning itself reads "getCurrentPosition() and watchPosition() are deprecated on insecure origins", which boilds down to pages served via HTTP and not HTTPS.
See, your code works fine here in the latest Chrome.
The easiest way to get SSL is probably to use Github pages for hosting your content or using something surge.
You could use the https://ipinfo.io API (it's my service) as an alternative to getCurrentLocation(). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more, works on non-SSL sites, and doesn't prompt the user for permission. Here's an example:
curl ipinfo.io
{
"ip": "172.56.39.47",
"hostname": "No Hostname",
"city": "Oakland",
"region": "California",
"country": "US",
"loc": "37.7350,-122.2088",
"org": "AS21928 T-Mobile USA, Inc.",
"postal": "94621"
}
Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
});
And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():
function do_something(coords) {
// Do something with the coords here
}
navigator.geolocation.getCurrentPosition(function(position) {
do_something(position.coords);
},
function(failure) {
$.getJSON('https://ipinfo.io/geo', function(response) {
var loc = response.loc.split(',');
var coords = {
latitude: loc[0],
longitude: loc[1]
};
do_something(coords);
});
};
});
See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.
In my AngularJS project I am using the following code to get a device's GPS co-ordinates:
// when user clicks on geo button
$scope.getGeoLocation = function() {
var geocoder = new google.maps.Geocoder();
window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = position;
var latlng = new google.maps.LatLng($scope.position.coords.latitude, $scope.position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.searchstring = results[2].formatted_address;
$location.search('s', $scope.searchstring);
$location.search('p', 1);
$location.search('geo', true);
$route.reload();
}
});
});
}, function(error) {
$scope.error = error;;
});
};
The problem is when location services is turned off on an iPhone 6, there is a no error created to inform the user that they need to turn on location services.
Does any one know how I can amend the code above to trigger an error in this scenario? Any help would be much appreciated.
As pointed out in this post Is there a way to check if geolocation has been DECLINED with Javascript?, you can pass a second callback to getCurrentPosition which will get called if the permission is declined.
Thanks for pointing me in the right direction unobf. Please find attached the code (with updated error handling) in case any one stumbles across this.
// when user clicks on geo button
$scope.getGeoLocation = function() {
var geocoder = new google.maps.Geocoder();
window.navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = position;
var latlng = new google.maps.LatLng($scope.position.coords.latitude, $scope.position.coords.longitude);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.searchstring = results[2].formatted_address;
$location.search('s', $scope.searchstring);
$location.search('p', 1);
$location.search('geo', true);
$route.reload();
}
});
});
}, function(error) {
$scope.error = "";
// Check for known errors
switch (error.code) {
case error.PERMISSION_DENIED:
$scope.error = "This website does not have permission to use " +
"the Geolocation API.";
alert("Geo location services appears to be disabled on your device.");
break;
case error.POSITION_UNAVAILABLE:
$scope.error = "The current position could not be determined.";
break;
case error.PERMISSION_DENIED_TIMEOUT:
$scope.error = "The current position could not be determined " +
"within the specified timeout period.";
break;
}
// If it's an unknown error, build a $scope.error that includes
// information that helps identify the situation, so that
// the error handler can be updated.
if ($scope.error == "")
{
var strErrorCode = error.code.toString();
$scope.error = "The position could not be determined due to " +
"an unknown error (Code: " + strErrorCode + ").";
}
});
};
I need to get users latitude and longitude from browser, but on most of browsers are some restrictions that doesn't let to do it. How to tell users that his geolocation is off or it simply doesn't support it?
I tried something like this, but neither ipad or safari on my mac prompt anything.
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(success);
else
alert('not supported');
DEMO: http://jsfiddle.net/7sRdS/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// ...
}, function(error) {
//error handling
switch(error.code) {
case error.PERMISSION_DENIED:
//User denied the request for Geolocation.
break;
case error.POSITION_UNAVAILABLE:
//Location information is unavailable.
break;
case error.TIMEOUT:
//The request to get user location timed out.
break;
case error.UNKNOWN_ERROR:
//An unknown error occurred.
break;
}
alert("Geolocation error: " + error.code);
},
{
timeout:10000 //10s
});
} else {
alert("Geolocation services are not supported by your browser.");
}
Take a look at modernizr which provides multiple feature detection tests.
I would like to hide() or show() a button that allows users to use their current location based on whether or not they are currently allowing location to be used in their browser setting.
the below code only checks if the browser supports geolocation and not whether or not the particular user is allowing it.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML="Geolocation is not supported by this browser.";}
}
Is there a boolean value that I can detect for their browser setting letting me know if location is currently allowed?
thanks for any suggestions.
Have you read http://www.w3schools.com/html/html5_geolocation.asp
What you want to do is check the errors to see if they allowed it or denied the request.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
The below code will allow you to check the permission status without invoking the navigator.geolocation permission request.
Browsers Supported: Chrome(43+), Firefox(46+), Edge and Opera.
Unsupported: Safari(mac, ios), Internet explorer, Android webview.
navigator.permissions && navigator.permissions.query({name: 'geolocation'})
.then(function(PermissionStatus) {
if (PermissionStatus.state == 'granted') {
//allowed
} else if (PermissionStatus.state == 'prompt') {
// prompt - not yet grated or denied
} else {
//denied
}
})
Here is the Reference Link.
Compatibility on other browsers is unknown. I haven't tested it myself but please feel to test yourself and comment below.