How can I get the latitude/longitude using the Ionic Framework. In Android it sometimes provides it as intended and sometimes it doesn't give latitude/longitude using the following:
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
You could use a call to a URL API which returns a JSON object, and then get the latitude and longitude. The following example calls http://freegeoip.net/json/ and prints out the results. To access the latitude and longitude, you would use the result.latitude and result.longitude fields.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://freegeoip.net/json/", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
this is an example how to get Lat,Long using https://github.com/apache/cordova-plugin-geolocation
.controller('MyCtrl', function($scope, $cordovaGeolocation) {
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + ' ' + long)
}, function(err) {
console.log(err)
});
var watchOptions = {timeout : 3000, enableHighAccuracy: false};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
console.log(err)
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
console.log(lat + '' + long)
}
);
watch.clearWatch();
})
You also noticed posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to true to get the best possible results but sometimes it can lead to some errors. There is also maximumAge option that can be used to show how old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.
Not quite sure what you are asking here, but Ionic can't give you geolocations, cordova however can. If you want to make it easy for yourself you should look into ngCordova, it's a angular wrapper for cordova plugins. Have a look here: http://ngcordova.com/docs/plugins/geolocation/
Related
this simple HTML code attached at the bottom, runs on Windows 11/Android 8 with no issues.
on Android 13, I am unable to run it.
I get -
ERROR(1): User denied Geolocation
the HTML file is located on the Galaxy S21 Internal storage and opened with Chrome.
I gave all permissions I know of, but no success.
I never got the prompt of "Allow access to your location".....
I am not an expert.
I would like to provide all the required permission in the HTML code itself, if possible.
thank you very much
<html>
<head>
<script type="text/javascript">
var x = document.getElementById("demo");
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
alert(`${crd.latitude} ${crd.longitude}`);
}
function error(err) {
alert(`ERROR(${err.code}): ${err.message}`);
}
function getLocation() {
//alert("getLocation")
if (navigator.geolocation) {
//alert("getLocation true")
navigator.geolocation.getCurrentPosition(success, error, options);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
alert(position.coords.latitude + "," + position.coords.longitude)
}
</script>
</head>
<body>
<p>
Click on the button to find your location.
</p>
<button onclick="javascript: getLocation();">Get my location</button>
<div id="demo">
</div>
</body>
</html>
By running the code below I have proven that Firefox on Android continues to track the user's location even when the phone is off and/or Firefox has been moved to the background and another App is in the foreground. How can the user tell that this espionage is occurring?
Should not a privilege/user-approval be required for this?
Why is Firefox the only browser with this vulnerability?
<!DOCTYPE html>
<html>
<body>
<p>Wait 5 secs.</p><br />
<p id="out"></p>
<script>
function success(position){
var x = document.getElementById("out");
x.innerHTML += position.timestamp+" GPS "+Date() + "<br />";
}
function failure(error){
var x = document.getElementById("out");
x.innerHTML += error+" Error "+Date() + "<br />";
}
document.getElementById("out").innerHTML = "Start "+Date()+"<br />";
if (document.addEventListener){
document.addEventListener("visibilitychange", function() {
var x = document.getElementById("out");
x.innerHTML += document.visibilityState +Date() + "<br />";
})
} else {
document.attachEvent("onvisibilitychange", function() {
var x = document.getElementById("out");
x.innerHTML += document.visibilityState +Date() + "<br />";
})
}
setTimeout(function(){
var x = document.getElementById("out");
x.innerHTML += "Timeout "+Date() + "<br />";
}, 5000);
trackerId = navigator.geolocation.watchPosition(success, failure, {
enableHighAccuracy: true
});
</script>
</body>
</html>
The Window.navigator read-only property returns a reference to the Navigator object......Its a JavaScript Object.......
Most browser will give a pop-up asking the user permission to allow the page to have access to user's geolocation when the script is run. Unless you have already allowed it. Use Menu > Settings > Clear private Data to clear site's data.
I'm using Phonegap Build to develop an application for iOS and Android.
I'd like to determine the locale (e.g. 'en-US') for the device, though I'd settle for the current language setting, or even the app store my app was installed from (it's been a long day).
Following the instructions here for the Globalization plugin I think I have everything right, but nothing seems to work on either the iPhone 6 or Samsung Galaxy Nexus I'm using for testing.
The relevant part of my config.xml looks like this:
<gap:plugin name="org.apache.cordova.globalization" />
My function for getting locale from the plugin looks like this:
var getPhoneGapLocaleName = function() {
var loc = 'unknown';
if (navigator.globalization !== undefined) {
navigator.globalization.getLocaleName(
function (locale) {
if (locale !== undefined) {
loc = locale.value;
}
},
function () {
// nothing
}
);
}
return loc;
};
Note: on both devices navigator.globalization.getLocaleName is present and appears correct, evaluating to a function resembling what I'd expect based on the documentation.
The problem here was that the variable 'loc' was declared outside the scope of the success or failure callbacks, which of course happen after a few brief moments.
I fixed this by changing the function thus:
var refreshPhoneGapLocaleName = function() {
if (navigator.globalization !== undefined) {
navigator.globalization.getLocaleName(
function (locale) {
if (locale !== undefined) {
localStorage['pg.locale'] = locale.value;
}
},
function () {
// nothing
}
);
}
};
Now calling it in onDeviceReady in order to refresh the values when the app starts.
A few moments later (not immediately) the following function can be used to retrieve the locale value:
var getLocale = function() {
return localStorage['pg.locale']();
};
The greatest thing about StackOverflow is how often it helps one to resolve one's own silly mistakes. :)
Although previous answers are returning the desired result, and giving an option to retrieve the current phonegap locale name, they did not explain the topic starter why his function did not work, and how to adjust his function to work in the way he intended (i.e. not using localStorage and not showing the locale in the console but giving the answer in real-time as a result)
I am posting this answer since I was looking for a quick function to get the device locale, and this post was my first result. While the opening post gave me everything I needed, I would like to answer this question for future visitors with the same purpose I had. Sorry for posting to a topic this old, but I hope I can help others with my answer.
The reason the function of topic starter does not work is the following: the plugin returns the locale in an asynchronous way. Therefore, the loc =locale.value line is only executed after the function's return statement. To fix this, we can write a wrapper function to simplify the plugins output as follows. Keep in mind that we need to use this function asynchronously, since the plugin result is also asynchronous.
The function:
var getPhoneGapLocaleName = function ( callback ) {
var unknownLocation = 'unknown'; //Default value
if ( navigator.globalization !== undefined ) {
navigator.globalization.getLocaleName(
function ( locale ) {
if ( locale !== undefined ) {
callback( locale.value );
} else {
callback( unknownLocation );
}
},
function () {
callback( unknownLocation );
}
);
} else {
callback( unknownLocation );
}
};
Use the function like this:
getPhoneGapLocaleName( function( loc ){ console.log( 'The locale was set as follows: ' + loc ); } );
Try this code
When the browser is set to the en_US locale, this should display a popup dialog with the text language: English:
navigator.globalization.getPreferredLanguage(
function (language) {alert('language: ' + language.value + '\n');},
function () {alert('Error getting language\n');}
);
Full Example
<!DOCTYPE HTML>
<html>
<head>
<title>getPreferredLanguage Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function checkLanguage() {
navigator.globalization.getPreferredLanguage(
function (language) {alert('language: ' + language.value + '\n');},
function () {alert('Error getting language\n');}
);
}
</script>
</head>
<body>
<button onclick="checkLanguage()">Click for language</button>
</body>
</html>
I am developing an app with phonegap(cordova) version 3.2 and I am having problems with mysql insertion. The following codes works well in browsers (mobile or not) but, when I run the app with an android emulator or in a real device it doesn't work.
The scripts:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0-rc.1/jquery.mobile-1.4.0-rc.1.min.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#formCadastro").submit(function(){
var campoNome = new String(document.getElementById("txtNome").value);
var campoEmail = new String(document.getElementById("txtEmail").value);
var campoUsuario = new String(document.getElementById("txtUsuario").value);
var campoSenha = new String(document.getElementById("txtSenha").value);
var campoSenhaConf = new String(document.getElementById("txtSenhaConf").value);
$.ajax({
type: "POST",
url: "http://imagect.co.nf/cadastra.php",
crossDomain: true,
data: { nome: campoNome , email: campoEmail, usuario: campoUsuario, senha: campoSenha}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
window.location="index.html";
})
.fail(function(jqXHR, msg) {
alert( "Errooo:" + msg );
alert( "Errooo:" + jqXHR );
console.log("Erro chato:" + msg);
console.log(jqXHR + " " + msg);
});
});
});
</script>
The problem is that neither the fail function nor the success function happens. It seems that android ignores the ajax...
I have already tried using deviceready, pageinit, mobileinit etc. But nothing works well.
The manifest has the internet permission and the config.xml has the access origin = *.
Could someone please help me?
Thanks, sorry about my English.
here is the code below
if (navigator.geolocation) {
alert("ok");
// var options = { timeout: 0, maximumAge: 600000 };
navigator.geolocation.watchPosition(onSuccess, onError);
}
function onSuccess(position) {
alert("success");
lat = position.coords.latitude;
lng = position.coords.longitude;
}
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
It works in all browsers , iphone and WindowsPhone. But in andorid in gives me error code :3 timeout expired error.
I enabled gps, wi-fi also in the settings menu--> location services -->location and Google Search,
In the browser menu settings--> privacy and settings enable location is checked.
What is the problem , any ideas? i really stuck in.
Normally , we accept the website request that wants to share your location.
In android if you do not see the question then in the browser settings advanced--> website settings add your URL to there.
It solves the problem.