Geolocation giving weird position sometimes - geolocation

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.

Related

Flutter app does not grab location afgsr gos is turned off then on

My application collects location data when the user presses on a certain button, but if the user turns gps option off then turns it back the location no more works even if the gps is enabled.How to handle such a thing in flutter??
As per example in this link https://pub.dartlang.org/packages/location you should put add below code in button's click event.
var location = new Location();
// Platform messages may fail, so we use a try/catch PlatformException.
try {
currentLocation = await location.getLocation;
} on PlatformException {
currentLocation = null;
}

Xamarin forms geolocator plugin working intermittently

We are trying to use the plugin "Xam.Plugin.Geolocator" in our Xamarin Forms project. The project is currently IOS only.
Our app returns a list of business based on the device users current location. We hit an API to return our JSON formatted list data and the API is functioning correctly.
We would like the list to update whenever the user pulls down, changes tab and when the page initially loads but currently this is only working once or twice in around 100 attempts. I've not found a pattern yet to why it's failing, or indeed when it works.
We set App Properties when the page loads, the tab is selected and the user refreshes like this -
public async void GetLocation()
{
try
{
locator = CrossGeolocator.Current;
if (locator.IsGeolocationAvailable && locator.IsGeolocationEnabled)
{
var position = await locator.GetPositionAsync();
App.Current.Properties["Longitude"] = position.Longitude.ToString();
App.Current.Properties["Latitude"] = position.Latitude.ToString();
}
else
{
await DisplayAlert("Location Error", "Unable to retrieve location at this time", "Cancel");
}
}catch(Exception e)
{
await DisplayAlert("Location Error", "Unable to retrieve location at this time","Cancel");
}
}
We call the above method in the three areas
1) when the page is loaded
public NearbyPage()
{
InitializeComponent();
GetLocation();
SetNearbyBusinesses();
NearbyBusinesses = new List<NearbyBusiness>();
SetViewData();
SetViewVisibility();
}
2) when the tab is clicked
protected override void OnAppearing()
{
base.OnAppearing();
GetLocation();
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
}
3) when the user pulls down to refresh
public void RefreshData()
{
if (!CrossConnectivity.Current.IsConnected)
{
NoInternetMessage.IsVisible = true;
return;
}
GetLocation();
NoInternetMessage.IsVisible = false;
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
_analyticsService.RecordEvent("Refresh Event: Refresh nearby businesses", AnalyticsEventCategory.UserAction);
}
Can anyone shed some light on what we're doing wrong or have experience with this plugin that can help us resolve this issue?
Thank you
EDIT
By "work", i mean that we'd like it to hit our API with the users current location data and return new results from the API every time the user pulls down to refresh, the page is loaded initially or when they press on a specific tab. Currently it works occasionally, very occasionally.
We can't debug with a phone connected to a macbook, as since we installed the geolocator plugin the app always crashes when connected. The app seems to work ok when deployed to a device, apart from the location stuff. We're currently deploying to test devices via Microsofts Mobile Centre.
Ok, so with the debugger always crashing and being unable to see any stack trace etc we took a few shots in the dark.
We've managed to get this working by adding async to our method signatures down through our code stack. This has resolved the issue and the geo location and refresh is working perfectly.
For example when we changed the above method 3. to refresh the data, it worked perfectly.
public async Task RefreshData()
{
if (!CrossConnectivity.Current.IsConnected)
{
NoInternetMessage.IsVisible = true;
return;
}
GetLocation();
NoInternetMessage.IsVisible = false;
SetNearbyBusinesses();
NearbyLocationsView.ItemsSource = NearbyBusinesses;
NoLocationsView.ItemsSource = UserMessages;
SetViewVisibility();
_analyticsService.RecordEvent("Refresh Event: Refresh nearby businesses", AnalyticsEventCategory.UserAction);
}
We refactored more of that code but adding async was what got it working.
I hope this helps someone else save some time.

Set timeout for notifications.notify FireFox Addon SDK

Please help me with Notification in my Firefox add-on.
var notifications = require("sdk/notifications");
function showNotifcation(title, text) {
notifications.notify({
iconURL: data.url("img/icon.png"),
title: title,
text: text
});
setTimeout(notifications.close(), 1000);
}
Not work.
Without more information from you it is not possible to be sure as to what your problem/issue is.
However, a brief look at the sdk/notifications documentation, and source code, indicates that you are attempting to use a non-existent method: notifications.close(). There is no such method in sdk/notifications.
One possible reason for your attempt to use this method is that you are conflating the Web Notification API, more detail, with the Add-on SDK sdk/notifications.
The Add-on SDK, sdk/notifications, has no way for you to programmatically close the notification from your code. Thus, there is no way for you to set a timeout for the notification using this interface. However, in some operating systems/windowing systems there is already a default timeout for these notifications.
You will need to either display a panel on your own, or use the chrome interfaces described in User Notifications and Alerts.
In addition, it would be unusual for you to be able to just call setTimeout(). That will, under most contexts, not be defined. You would normally need to use sdk/timers with:
var { setTimeout } = require("sdk/timers");
In some contexts, you might be able to use window.setTimeout(), when window is appropriately defined (which you will probably have to set yourself).
Modifying the code from my answer to Prevent XUL notificationBox from closing when button is hit (if you want buttons, that answer will show you how to do it), and other answers of mine: Something along the lines of what I believe you desire would be (code for the timeout is at the bottom):
function showNotificationBox(text) {
//Create some common variables if they do not exist.
if (window === null || typeof window !== "object") {
// Add/remove a "/" to comment/un-comment the code appropriate for your add-on:
//* Add-on SDK:
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
/* Overlay and bootstrap (from almost any context/scope):
var window=Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//*/
}
if (typeof gBrowser === "undefined") {
var gBrowser = window.gBrowser;
}
let notifyBox = gBrowser.getNotificationBox();
//appendNotification( label , value , image (URL) , priority , buttons, eventCallback )
let theNotification = notifyBox.appendNotification(text, "Test notification unique ID",
"chrome://browser/content/aboutRobots-icon.png",
notifyBox.PRIORITY_INFO_HIGH, [], null);
//* Add-on SDK:
var { setTimeout } = require("sdk/timers");
setTimeout(theNotification.close(), 10000);
//*/
/* Overlay and bootstrap:
let timerCallback = {
notify:function notify() {theNotification.close(); }
}
let closeNotificationTimer = Components.classes["#mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
closeNotificationTimer.initWithCallback(timerCallback,10000,
Components.interfaces.nsITimer.TYPE_ONE_SHOT);
//*/
}
Note: I changed the timeout to 10 seconds from the 1 second which is in the code in your question. One second is a unreasonable amount of time to expect to show anything which you actually desire the user to see and understand.
The above implements the user notification in a notificationBox. As such it shows up within the Firefox window:
It is also possible to use the nsIAlertsService which is what sdk/notifications uses. This will normally display an alert box in the bottom right of the screen, potentially outside of the Firefox window (see image on nsIAlertsService for example). The notification may show up elsewhere depending on how you have your windowing system set up (this is OS dependent). However, the documentation did not have a method to clear the notification, or set a timeout. However, the interface definition does show that a closeAlert() method does exist. The source code for the sdk/notifications does not expose this to the Add-on SDK. Thus, you would need to use the chrome interfaces. I have updated the documentation to show closeAlert().
Such as (some code taken and modified from nsIAlertsService):
//* Add-on SDK:
var {Cc, Ci} = require("chrome");
//*/
/* Overlay and bootstrap:
const Cc = Components.classes;
const Ci = Components.interfaces;
//*/
function showNotifcation(title, text) {
var alertsService = Cc["#mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
try {
//The second use of title is the alert name.
alertsService.showAlertNotification(icon, title, text, false, "", null, title);
} catch (e) {
// This can fail on Mac OS X
}
//* Add-on SDK:
var { setTimeout } = require("sdk/timers");
setTimeout(alertsService.closeAlert(title), 10000);
//*/
/* Overlay and bootstrap:
let alertTimerCallback = {
notify:function notify() {alertsService.closeAlert(title); }
}
let closeAlertTimer = Cc["#mozilla.org/timer;1"].createInstance(Components.interfaces
.nsITimer);
closeAlertTimer.initWithCallback(alertTimerCallback,10000,Ci.nsITimer.TYPE_ONE_SHOT);
//*/
}
I have only tested the above code with a bootstrapped/restartless Firefox add-on. Thus, the Add-on SDK code may be slightly off.

how to make wl.device.geo.acquireposition run in background

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

Phonegap, Cordova watchposition fire success every 1 second

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);
}

Resources