Javascript browser navigator permissions else section not triggering - javascript

Have a small javascript piece of code which calls navigator.geolocation.
I have an if statement, which works, to show the latitude and longitude if the user the user allows the call. However, the else section is not running.
If I run the code below I get prompted by the browser to allow; if I allow it then coordinates are shown. However, if I hit block instead nothing happens even though there is an else section.
<body>
<br> <p id="ChangeSring">Test</p>
<script>
var x = document.getElementById("ChangeSring");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(SavePosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
function SavePosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.cookie = 'location=true;path=/form_handler';
document.cookie = 'latitude='+ position.coords.latitude +';path=/form_handler';
document.cookie = 'longitude='+ position.coords.longitude +';path=/form_handler';
}
</script>
<form action="/form_handler" _lpchecked="1">
Enter value:
<input type="text" name="SomeVar"><br>
<input type="submit" value="search">
</form>
</body>

You cannot use else to check for permissions.
The navigator method getCurrentPosition takes a success and error callbacks.
The error callback will be called if permission is denied.
if (navigator.geolocation) { // this checks if navigator is supported at all
navigator.geolocation.getCurrentPosition(console.log, () => {
console.log('Permission denied')
});
} else {
console.log('Geolocation is not supported by this browser.');
}

getCurrentPosition takes a success and an error function.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#Example
function errorGettingPosition(positionError) {
x.innerHTML = "Geolocation is not supported by this browser.";
document.cookie = 'location=false;path=/form_handler';
}
navigator.geolocation.getCurrentPosition(SavePosition, errorGettingPosition)

That if-else statement is checking if navigator.geolocation it's not undefined(and it's not even if you don't want the browser to know your location) follow the other answers to properly handle permission

Related

GPS location is fetched after second click not on first click

I want to fetch live gps location using javscript to store it in database. I already have implemented it. when user clicks on button. But it fetches location on second click.
Html code
<form action="user_location" method="post" id="form-{{$user->id}}">
#csrf
<input type="hidden" name="id" value="{{$user->id}}">
<input type="hidden" name="location" id="location-{{$user->id}}">
</form>
<a onclick="getLocation({{$user->id}})" class="btn">{{__('Get Location')}}</a>
Javscript code
function getLocation(user_id) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
geolocation = "Geolocation is not supported by this browser.";
}
if(setlocation){
form = document.getElementById("form-"+user_id);
var b = document.getElementById("location-"+user_id)
b.value = x.textContent;
form.submit();
}
}
function showPosition(position) {
x.innerText = position.coords.latitude + "-" + position.coords.longitude;
setlocation = true;
}
The getCurrentPosition function is asynchronous. That means that when it is called, it will allow the code after it to run before finishing. So that means that setLocation will not be true whenever your code reaches the following if statement:
if(setlocation){ // setlocation is still false
Handle your results of getting the position inside the success callback of getCurrentPosition.
function getLocation(user_id) {
if (!navigator.geolocation) {
return;
}
const form = document.getElementById("form-" + user_id);
const location = document.getElementById("location-" + user_id);
navigator.geolocation.getCurrentPosition(function(position) {
const { coords } = position;
location.value = coords.latitude + "-" + coords.longitude;
form.submit();
});
}

Get current location in JS/PHP

I am trying to get current location (with address, not only lat, long), But i am stuck that how to get?
Here is the code:
<button onclick="getLocation()">Click Me</button>
<div id="address"></div>
<script>
var x = document.getElementById("address");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
It's returning only latitude and longitude. But i need full address like Model town 30-A, Lahore or something like this address.
Here is the site which has this kind of functionality: https://gps-coordinates.org/my-location.php.
To check, open this link and see in the Address input.
Please help me. How can i get current address?

Wanting to get a devices GPS location using getCurrentPosition() or something of the like and get the results back into PHP

I'm trying to get the location of a device at the time of loading a web page and passing that through to two variables in PHP (lat, long) so it can be manipulated further down the script. Currently, I have the data entered manually by tasker through the URL, but I'd like to have it available in a normal web page too without having to put the data into the URL by hand each time.
I was trying to use the getCurrentPosition() JavaScript to do this, but I can't find a way to get it back into the PHP. I have tried to write two separate files but all I seem to get back from the file is the JS script because it has not yet processed the file. So not the actual data itself.
PHP File:
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
ob_start();
$location = file_get_contents('https://myfakeurl.com/getlocation.php', false, stream_context_create($arrContextOptions));
$GPSCoord = explode(",", $location);
$coord['lat'] = trim($GPSCoord[0]);
$coord['long'] = trim($GPSCoord[1]);
echo "Longitude: " . $coord['long'] . "<br>";
echo "Lattitude: " . $coord['lat'] . "<br>";
?>
and JS file:
<p id="coord"></p>
<script>
var x = document.getElementById("coord");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + "," +
position.coords.longitude;
}
getLocation()
</script>
The JS needs to run on the devices too which is part of the problem otherwise you don't get the correct GPS coords
How can I make this work? I feel like this is an Alice in Wonderland rabbit hole...
The js code will not run if you use php's file_get_contents function, because of javascript is client side language. It's necessary to open the page from browser to run javascript. You can place javascript code on loaded webpage, catch location data and send to php with ajax. Try something like this
backend.php
<?php
if(isset($_POST['lng'], $_POST['lat'])) {
echo $_POST['lng'].':'.$_POST['lat'];
}
?>
frontend.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="response">
</div>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(sendPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function sendPosition(position) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://fakeurl/backend.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lng="+position.coords.longitude+"&lat="+position.coords.latitude);
document.getElementById('response').innerHTML = xhttp.responseText;
}
getLocation();
</script>
</body>
</html>

Why does HTML5 Geolocation have inconsistent errorneous behavior in different web browsers

I have been testing a simple code fragment which returns the longitude and latitude values using the HTML5 Geolocation feature:
var x = document.getElementById("demo");
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;
}
}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
I tested the code in Google Chrome directly from the 'Try it out' section and it returned 'error.PERMISSION_DENIED'. But it worked, when I deployed it in XAMPP under the localhost. Note that I have setup Google Chrome to share location details based on this documentation.
But this code returns 'error.POSITION_UNAVAILABLE' in Firefox even when deployed in XAMPP and when I agree to share my location in Firefox.
What causes this inconsistent behavior in Google Chrome (when called directly and when deployed under localhost) and when accessing through Firefox?
For sharing location you need secure connection. More: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins

How to have a text display of your current location on a Webpage

Entry question on what to do / where to look further for this possibly easy facility for a Website
I basically want to show the my current geographic location via a text display, not as a display on Google Maps. Obviously I would like this to update automatically
Does anyone know a program that would facilitate this? Or generally the best way to go about it?
You can use this code to update your page with the current location:
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
<div id="demo"></div>

Categories

Resources