js geolocation but without prompting - possible? - javascript

Is it possible to get the geolocation of a user without the browser prompt?
Here's the code sample from W3
<script>
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;
}
</script>
Is there any preventPrompt()-like function ?

No you cant prevent the prompt, its a security feature cause not every user wanna share its location.
From the W3C docs:
A conforming implementation of this specification must provide a
mechanism that protects the user's privacy and this mechanism should
ensure that no location information is made available through this API
without the user's express permission.
But you can try to use a service like geoip in the error callback.

No, that's not possible.
The prompt is there so that the user can choose whether you know the location or not.

Related

How to get username from authentication prompt popup

I have SharePoint Online classic page which has some custom JavaScript and jQuery scripts implemented and third party .NET app requiring some basic auth. When the user visits the page he is prompted to enter username and password. How can I get the username from this prompt? Prompt is standard and looks like this (picture is not mine)
You can use SharePoint's javascript API to retrieve the current user's information.
_spPageContextInfo.userId
see: https://social.technet.microsoft.com/wiki/contents/articles/29766.sharepoint-understanding-the-sppagecontextinfo-object.aspx
Another suggestion is to use the API:
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getCurrentUser, "sp.js");
var currentUser;
function getCurrentUser(){
var ctx= new SP.ClientContext.get_current();
var web = ctx.get_web();
currentUser = web.get_currentUser();
ctx.load(currentUser);
ctx.executeQueryAsync(onSuccess, onFailure);
}
function onSuccess() {
alert(currentUser.get_title()); // Domain\Account
alert(currentUser.get_email());
document.getElementById('userLogin').innerHTML = currentUser.get_loginName();
}
function onFailure() {
alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
<div>Currently Logged User:
<span id="userLogin"></span>
</div>
MS reference: https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-sharepoint-client-library-code
If someone is still interested in this I found a way to get the user principal name with microsoft graph API https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http
https://graph.microsoft.com/v1.0/me?$select=mailnickname,onpremisesUserprincipalName was the actual request I needed

Django web app that detects a smart-phone user's position

I want to build a web app using Django-Python that will be mainly used from smart-phones. I want the app to be able to detect the user's position and showcase it into a google maps front end. Basically, I want the app to be something like google maps GPS and then I will make some calculations with the coordinates and print out to the user some alternatives. I want the user's coordinates to be updated when he walks for example.
Do you have any suggestions about what modules, libraries or packages can I use to get this done? I found some packages like djangocms-gmaps but I am not sure if this is the right way to go.
This is not a function provided by Django. More javascript anf HTML5
Here is a example snippet that you ofcourse can use with a Django project.
<script>
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;
}
</script>

How to find my real latitude and longitude using JavaScript code?

I want to find my latitude and longitude using PHP.
I have tried multiple ways, but my solutions only show the service provider location and IP address. I want to find my real latitude and longitude.
I am using the below code but it's not working for me.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
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;
}
</script>
</body>
</html>
navigator.geolocation will generally use the most precise data available to the browser.
If the client has a GPS (as phones tend to) then it will probably use that.
If it has Wi-fi, then it may be able to use nearby access points to determine the location.
If it has to fallback to GeoIP lookups, then it will only be a precise as the data held on the ISP.
You are currently suffering from using a client which is using the last of the above. You can't get more precise than that without changing the client.

Check if user device's GPS is on

I am developing an app using jQuery Mobile with PHP. I am not using Phonegap or other frameworks. I need to find user's geolocation. If user device's GPS is off, then I cant get a location. now I need to find user device's GPS is on or off.
this is what i using now.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat=position.coords.latitude;
var long=position.coords.longitude;
}
You can call this function on load
// Function to get location
function getLocation(){
navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
if (lat == null) {
alert("GPS not activated!");
} else {
alert("Latitude: "+ lat + " , Longitude: " + lng );
}
});
}
There is no way to check if the device has a GPS module or if it has it enabled through the browser's API. Your laptop will, for example, try to estimate the position based on the IP address with very poor accuracy.
You can, however, use a trick that will likely be good enough for many applications: instead of using the getCurrentPosition(), use the watchPosition() function with an options object { enableHighAccuracy: true } and set a threshold of accuracy that the measurement has to reach for you to accept it as most likely a result based on the GPS module.
What happens when you start to listen to the watchPosition() with enableHighAccuracy set to true is that if GPS module is available, the API will let it know that you're trying to get a measurement and after up to a few seconds the accuracy distance will go from very high (often thousands of meters - based on IP address, cell tower triangulation, etc.) to a very low (few meters - based on the GPS) and that means that the GPS kicked in. If the accuracy stays at hundreds or thousands of meters, it probably means that there is no GPS module available.
Here's the documentation for the GeolocationCoordinates object (the result within the callback passed to the watchPosition()) which comes with the accuracy field. I wrote a longer post that also contains a code snippet showing how I use the API within React.
I just solved this one. I am using:
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge: 60000});
In the successCallback i written the codes for what it should do once I got the positions and in the error callback i wrote a simple alert message to prompt the user to turn the GPS on.
I Implemented This In Real World Project
KMaps-API GPS.js
<script>
function getLocationw() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPositionw);
} else {
x.innerHTML = "Something Is Wrong";
}
}
function showPositionw(position) {
lat = position.coords.latitude;
if(lat != null){
document.write('<center><div class="alert alert-info" role="alert"> Please Turn On Your GPS </div></center>')
}
}
getLocationw();
</script>

Get coordinates from Hardware GPS

I've found a lot of questions about GPS Coordinates but not one that confirms using the mobile hardware GPS instead of Web GPS like geoLocation and such like.
My actual method:
I'm using navigator.geolocation.getCurrentPosition(), the Lat/Long comes from the Web, here's the code:
function getGPS(funcCallBack)
{
if (navigator.geolocation)
{
var timeoutVal = getCookie("GPSTimeout");
navigator.geolocation.getCurrentPosition(sucess
,error
,{enableHighAccuracy: true
,timeout: timeoutVal
,maximumAge: 0}
);
}
else{
alert('GPS is turned off, or was not possible to find it. Now, doing the login without localization.');
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
function sucess(position) //sucess
{
window.gpsLat = position.coords.latitude;
window.gpsLng = position.coords.longitude;
window.gpsAcc = position.coords.accuracy;
funcCallBack();
}
function error() //error
{
window.gpsLat = 0;
window.gpsLng = 0;
window.gpsAcc = 0;
funcCallBack();
}
}
My problem:
Sometimes when I do the login I am not getting the GPS Coordinates (they come 0) and sometimes I am getting coordinates with more than 2,000 Accuracy (that is not precise).
By the way, I am testing the GPS on a data internet service, when I do use a Wi-Fi connection it works perfectly with less than 100 Accuracy.
Details:
Maybe you are complaining about:
timeoutVal: it is a cookie with the number 5000 inside it.
funcCallBack: it is a function that continues the login operation.
window.gpsLat: it is a global var containing the Latitude value got from the geoLocation.
window.gpsLng: it is a global var containing the Longitude value got from the geoLocation.
window.gpsAcc: it is a global var containing the Accuracy value got from the geoLocation.
What do I want?
I want a solution in JavaScript or PHP that can get coordinates from the mobile hardware device, the Native GPS, not the geolocation, and when the Native GPS is turned off, ask the user to turn it on.
You should get the location with javascript not PHP. PHP is only capable of doing an IP lookup which is the least accurate method for determining location.
The way navigator.geolocation.getCurrentPosition() works is it uses the most accurate data currently available. In the case of a mobile device it will use GPS first if enabled, then wi-fi.
If native GPS is enabled javascript will access that data instead of the wi-fi data, but there is no way of preventing a check against the wi-fi data if the GPS data isn't available.
Your best solution is to check the accuracy field and if it's not within a range you're happy with ask the user to enable GPS.
Alternatively if you're building a hybrid app, most of the frameworks (PhoneGap .etc.) have APIs to query the device GPS directly. Use PhoneGap to Check if GPS is enabled
Geolocation API does not expose a direct way to check whether GPS is on or off, but you can catch the errors of geolocation and base on error type can draw conclusions from there.
E.g. POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.
But its not sure short way you have to handle some conditions!
I will suggest use watchPostion { i agree its meant to watch and continuous to locate position} u can keep it on and if GPS throw the error u can prompt custom alert to make user turn on the GPS device/wifi/internet .. and if its come to success callback u can clear the watch.
var watch =null;
function success(position)
{
var lat = position.coords.latitude;
var lon= position.coords.longitude;
if (watch != null )
/*Need to take care .. as maybe there is no gps and user
want it off so keep attempt 3 times or some kind a way out otherwise it will
infinite loop */
{
navigator.geolocation.clearWatch(watch);
watch = null;
}
}
function getLatLon()
{
var geolocOK = ("geolocation" in navigator);
if ( geolocOK )
{
var option = {enableHighAccuracy:true, maximumAge: 0,timeout:10000 };
watch = navigator.geolocation.watchPosition(success, fails, option);
}
else {
//disable the current location?
}
}
function fails()
{
alert("please turn on the GPS !");
}
getLatLon();

Categories

Resources