To detect current geo location in mobile device - javascript

I've used below code to detect the current location in angular app. this is working fine with all the desktop browser but it not working in mobile device please find below code for more understanding.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onPositionUpdate,locNotFound,{frequency:5000,maximumAge: 0, timeout: 100, enableHighAccuracy:true});
} else {
// nothing
}
function locNotFound () {
console.log('location not found');
}
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true";
$http.get(url)
.then(function(result) {
console.log(result);
});
}
As you can see that locNotFound() function is called in mobile device. which it should not do because GPS on in mobile device.

I just can give you a partial answer for Android.
Please open the Chrome Browser at Android, click at the icon top right (the tree dots), click at Settings, click at Site Settings and please check the settings for Location. As far as I know this is disabled per default.
So I think your problem is related to security restrictions
Regards
Michael

Related

Script not working on inactive tab

I have script for geolocalization. It's working only when user is on website. When browser is miminalized or tab is inactive, script is not working. How can I fix it?
var int=self.setInterval(function(){getLocation()},2000);
function getLocation()
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log('Position: '+latitude+' '+longitude);
$.ajax({
type : "POST",
data : { latitude : latitude, longitude : longitude },
url : "mylinktosaveposition",
success : function(data){}
});
}
This is a security feature built into browsers, there is no way to get around this! Browsers simply freeze or shut down scripts when they go inactive to increase performance on active tabs and reduce power usage on battery powered devices. I would recommend creating an app if you are looking into geotracing people for whatever reason. Take a look at ionic which is a framework on cordova which uses angular to built apps for ios and android in javascript/html like language.

html geolocation: Unknown error acquiring position

I am trying to use HTML geolocation to get my position. Funny thing is, it was working brilliantly until some seemingly random point in the day when it just stopped working. Now all I get is the error callback with a message:
Unknown error acquiring position
This happened on the day I first started to develop the app. It is a web app built in Node/Express. The browser I am using is Firefox v53 64-bit.
Location is allowed, and I have also tried a fix that I found online which involves going to about:config and changing geo.wifi.uri from:
https://www.googleapis.com/geolocation/v1/geolocate?key=%GOOGLE_API_KEY%
to
https://www.googleapis.com/geolocation/v1/geolocate?key=test
This did not work for me.
This does however work on my phones Firefox app, but not the Google Chrome app.
Heres an example code snippet:
const geo = navigator.geolocation;
geo.getCurrentPosition(success, failure);
function success(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
$('#coords').val(lat + ',' + lng);
mapView.setCenter(ol.proj.fromLonLat([lng, lat]));
}
function failure(error) {
console.log(error.message);
}
The full page: https://github.com/ThriceGood/Spots/blob/master/views/index.html
Can anyone shed some light on this issue?
What worked for me was changing geo.wifi.uri to:
https://location.services.mozilla.com/v1/geolocate?key=test
As per this page: navigator.geolocation.getCurrentPosition do not work in Firefox 30.0

javascript - geolocation not working in codepen

I'm trying to implement a simple weather app in codepen. The app works fine on localhost
It asks for permission to use navigator.geolocation and if accepted it shows the weather,
but on codepen it's not even asking for permission.
here is the link
http://codepen.io/asamolion/pen/BzWLVe
Here is the JS function
function getWeather() {
'use strict';
$('#getWeatherButton').hide();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var url = 'http://api.openweathermap.org/data/2.5/weather?APPID=53ac88144e6ee627ad0ed85277545ff9';
// var url = 'example.js';
var apiCall = url + '&lat=' + position.coords.latitude + '&lon=' + position.coords.longitude;
// window.location.href = apiCall;
$.getJSON(apiCall, function (json) {
setSkycon(parseInt(json.weather[0].id, 10));
$('#location').html(json.name + ', ' + json.sys.country);
var temp = (Math.round((json.main.temp - 273.15) * 100) / 100);
$('#temp').html(temp + '<span id="degree">°</span><span id="FC" onclick="convert()">C</span>');
$('#condition').html(json.weather[0].main);
});
});
}
};
Can anybody tell me why codepen is not asking for permission?
I had this same problem on the same challenge. Simply prepend your codepen with https instead of http and you'll be fine.
Like this:
https://codepen.io/crownedjitter/pen/AXzdvQ
if you want to use this:
navigator.geolocation.getCurrentPosition();
in Chrome.
According to the console in Chrome:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.
There's more details here: https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins Essentially Chrome only wants to send location information over HTTPS. However, in order to allow developers to test they treat localhost as if it were a secure network. Hope this helps!
Starting with Chrome 50, Chrome stopped supporting geolocation on unsecured protocols.
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only

Android geolocation not responding right after turning location on

I have the following simple code:
$(document).ready(function() {
$('#btn').click(function () {
navigator.geolocation.getCurrentPosition(function (position) {
$.post('serverhandler.php', { 'lat' : position.coords.latitude, 'lng' : position.coords.longitude }).done(function (data) {
alert(data);
});
}
,handle_errors
);
});
});
With this I get the location of the user, and it works ok if the location is already on in the mobile settings.
The thing is that if the user enters the site with the location off and turn it on when asked, the android mobile doesn't send anything. It can be fixed by opening google maps and retrieving its location, and then going back to the website, but I'd like a way to do so within the site.
The same code works fine on the same conditions with IOS, and windows phone retrieves the wrong location, with the same fix of android(but with here maps instead of google maps). Any ideas on why it works like that and some way to work around it? Thanks!

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

Categories