Platform: iOS6/OSx Lion.
I'm trying to puzzle out the way Phonegap/Cordova work with navigator.geolocation.watchPosition.
The docs says that the option "maximumAge" is the one that ask the system for retrieve the position.
So with these options:
{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }
I espect the position request will be fired every 3 seconds?
And no matter what maximumAge I put the success is fired every 1 second...
Anyone can explain please?
Thanks Bye
Rob
I am currently working around this issue by using getCurrentPosition with a setInterval. I'm not sure what the consequences may be, but this seems to give me the most control and appears to be the most consistent method across platforms.
// call this once
setupWatch(3000);
// sets up the interval at the specified frequency
function setupWatch(freq) {
// global var here so it can be cleared on logout (or whenever).
activeWatch = setInterval(watchLocation, freq);
}
// this is what gets called on the interval.
function watchLocation() {
var gcp = navigator.geolocation.getCurrentPosition(
updateUserLoc, onLocationError, {
enableHighAccuracy: true
});
// console.log(gcp);
}
// do something with the results
function updateUserLoc(position) {
var location = {
lat : position.coords.latitude,
lng : position.coords.longitude
};
console.log(location.lat);
console.log(location.lng);
}
// stop watching
function logout() {
clearInterval(activeWatch);
}
Related
I am currently learning react-native and I am working on a an application that uses Geolocation to find and update my current location and I am following a tutorial for that and in the tutorial I had to use a property with the timeout and maximumAge options.
navigator.geolocation.getCurrentPosition((pozitie)=>{
var lat = parseFloat(position.coords.latitude)
var long = parseFloat(position.coords.longitude)
// create an object with the current position taken from the geolocation chip
var initialLocation = {
latitude = lat,
longitude = long,
// Delta is the viewing angle on the location of the user
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}
// Now we are seting initial position to the initial location
this.setState({initialPositionOnTheMap: initialLocation})
// we set the marker to the initial location and then the display follows the marker
// by using the initialLocaiton object that will receive the users current location
this.setState({positionOfTheMarker: initialLocation})
},
// make a function call if an error happens
// we make an allert that parses the error message
(error) => alert(JSON.stringify(error)),
// propertie
{enableHighAccuracy: true, timeout: 2000, maximumAge: 1000})
but it didn't explain what does timeout and maximumAge mean, why do we use them.
I know that these options are used in two methods provided by react-native: getCurrentPosition(Invokes a callback with the latest location) and watchPosition(Invokes a callback whenever the location has changed) but I don't understand what are they doing exactly.
I have asked the creator of the tutorial, and he responded:
Timeout: is a positive value that indicates the maximum time the device is allowed to return a position.
MaximumAge: is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. In other words, how old can cached locations be before I should start getting the current location to return.
Hi guys I need some help on how to get the coordinates of the user when you enable the
followUserLocation
on
MapView
. Is there a way on how to do this or are there any possible alternatives to this?
I already did something like this:
import {DeviceEventEmitter} from 'react-native';
import RNALocation from 'react-native-android-location';
import MapView from 'react-native-maps';
componentDidMount() {
DeviceEventEmitter.addListener('updateLocation', function(e: Event) {
console.log(e);
this.setState({lng: e.Longitude, lat: e.Latitude });
}.bind(this));
RNALocation.getLocation();
}
Already used React Native Geolocation https://facebook.github.io/react-native/docs/geolocation.html
but nothing seems to work. It only gives me the initial location of the user and it does not give me some updates when there are changes on user location.
I even used setInterval to keep on calling the API so it can give me new updates on the user location but the coordinates still does not change.
I used fake GPS to move my location or mock my location . . please help thanks a lot.
You can use navigator.geolocation.watchPosition (https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition)
const options = options = {
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.watchPosition((lastPosition) => {
this.setState({lng: lastPosition.coords.longitude, lat: lastPosition.coords.latitude });
}, (error) => {
console.log('Error', error)
}, options);
Anyways, I got it all sorted out. Since there is no way I can listen to user location using the GPS of the mobile device. What I did was I used the code from React Native geolocation
navigator.geolocation.getCurrentPosition(
(position) => {
var initialPosition = JSON.stringify(position);
this.setState({initialPosition});
},
(error) => alert(JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
Loop through it every 1 second and then update the coordinate states (lat and long) if there is a change in coordinates. So far it works smoothly. :)
I´m working on a worklight (now mobileFirst) app ment to work on Android and iPhone. One of the issues is that i need to locate the user in some points, in order to notify him/her with a local push notification. Everything seems to work fine while the app is on foreground, but i also need it to work while on background.
i´ve checked the following links among others but nothing works for me yet:
https://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/devref/t_keeping_app_running_in_background.html
https://www-01.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_wl_location_geoAcquirePosition.html
This is my code if it helps:
function getFirstPositionAndTrack() {
// use GPS to get the user's location
var geoPolicy = WL.Device.Geo.Profiles.LiveTracking();
geoPolicy.timeout = 60000; // set timeout to 1 minute
geoPolicy.maximumAge = 10000; // allow to use a position that is 10 seconds old
// note: to see at high-accuracy, change RoughTracking above to LiveTracking
// get the user's current position
WL.Device.Geo.acquirePosition(
function(pos) {
// when we receive the position, we display it and start on-going acquisition
WL.Logger.debug("acquired position");
WL.Logger.debug("Longitude: " + pos.coords.longitude);
WL.Logger.debug("Latitude: " + pos.coords.latitude);
var triggers = new Object();
triggers.Geo = {};
var trigger_events = generateTrigger();
triggers.Geo = trigger_events;
WL.Device.startAcquisition({ Geo: geoPolicy }, triggers, { Geo: alertOnGeoAcquisitionErr } );
},
function(geoErr) {
alertOnGeoAcquisitionErr(geoErr);
},
geoPolicy
);
}
//Method that create triggers dinamically
function generateTrigger() {
var trigger_events = new Object();
angular.forEach(json.locations, function(location) {
var trigger = {
type: "DwellInside",
circle: {
longitude: location.longitude,
latitude: location.latitude,
radius: 100
},
dwellingTime: 3000,
callback: function() {
// WL.Logger.info("Enter branch");
// WL.Client.transmitEvent({ branch: "enter branch"}, true);
console.log("Location: "+JSON.stringify(location));
alert("We are in: "+location.name);
}
};
trigger_events["dwellArea_"+location.name] = trigger;
});
return trigger_events;
}
I´m actually trying on iOS, and my info.plist file looks like this:
What i get is nothing while on background, but when i´m back to foreground it seems like i get everything at once. So, it looks like it actually does something, but it doesn´t let you know until you go back to foreground... is there way to keep the worklight process active while on background?
Any help will be appreciated, thanks in advance!
So if I understand the question correctly, you are attempting to make "local notifications" but no where in the code supplied do you show how are you attempting to do that?
Anyway, local notifications are only possible via a Cordova plug-in. See here:
How can i create local Notification in worklight
Using katzer local notification in IBM Worklight
For showing a loading screen, we listen to the jQuery ajaxStart() event the following way:
$(document).ajaxStart(function() {
//show loading screen
});
However, this event doesn't get fired sending forge.reques.ajax() requests (at least is seems so).
Is there already a solution like that for forge or do I have to write that event by hand?
This doesn't currently exist in forge, but its pretty easy to implement:
var onAjaxStart = function () {
// show loading screen
}
var onAjaxEnd = function () {
// hide loading screen
}
var myAjax = function (params) {
onAjaxStart();
var success = params.success;
params.success = function () {
onAjaxEnd();
success && success();
};
forge.request.ajax(params);
}
Then us myAjax(...) instead of forge.request.ajax(...).
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean(); // Try W3C Geolocation (Preferred)
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // THERES OUR LAT/LONG VALUES
ajaxPost(initialLocation);
},
function() {
handleNoGeolocation(browserSupportFlag);
}); // Try Google Gears Geolocation
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude, position.longitude); // THERES OUR LAT/LONG VALUES
ajaxPost(initialLocation);
},
function() {
handleNoGeoLocation(browserSupportFlag);
}); // Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
initialLocation = new google.maps.LatLng(geoip_latitude(), geoip_longitude()); // THERES OUR LAT/LONG VALUES
ajaxPost(initialLocation);
navigator.notification.alert('Geolocation service failed', // message
'Geolocation Error!', // title
'OK' // buttonName
);
} else {
initialLocation = new google.maps.LatLng(geoip_latitude(), geoip_longitude()); // THERES OUR LAT/LONG VALUES
ajaxPost(initialLocation);
navigator.notification.alert("Your browser doesn't support geolocation. We've placed you in Siberia.", // message
'Browser Error!', // title
'OK' // buttonName
);
} // THERES OUR LAT/LONG VALUES
}
This is code we use in our Sencha Touch application to get the users current position. Now, I tested this code using a 3G connection on my Droid HTC Eris, and it gave me a location 6 miles away from myself, which is fine, I can live with that, I could probably even live with a little bit more.
However, testing on an iPod Touch using Wifi, connecting to our in home router, it put us 147 miles from our current location. Now, this might make sense if our router here had some weird IP address or something like that (w/e this code actually uses to find location if it doesn't fall back to IP), but I testing geolocation straight from google from a laptop also hooked up to our wifi here and it puts us less than 1 mile from overhead.
What kind of situation could make this happen? Is this something we are just going to have to live with until geolocation further advances? If so, that's fine, I just want to know if there's something we could do to improve this. 147 miles away is a little crazy, considering every other source we've tried puts us within 10 max.
The only thing I can think of is that google has some correction listings in it's own databases. What is probably happening is your ip is registered to a holdco which is 147 miles away from you. For example if whois my IP it is registered to a holding company which is about 50 miles away from me. Non-corrected databases (such as the ones you typically buy online) show me in that town. Google, whoever does not.