Heey People,
I've wrote something to find the gps location of my iphone.
If my location is found it should show my location in an alertbox.
But apparently it keeps showing me the alertbox on my iphone over and over again.
I've wrote my class so that I can set an callback function.
Because when you try to get your location it is not set till your found.
The callback function will be executed when your location is found.
Can anyone tell me how to stop the location tracker after I'm found?
My class:
GPS = function() {
this.constructor();
}
var gpsLatitude = 0.0, gpsLongitude = 0.0, gpsCallback;
GPS.prototype.constructor = function(){
this.getLocation();
}
var afterNotification = function(){
//Do something
};
GPS.prototype.setCallback = function(myfunction){
gpsCallback = myfunction;
}
GPS.prototype.getLocation = function(){
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(this.showPosition, this.showError);
}
else{
Lungo.Notification.error(
"Error", //Title
"Your device doesnt support GPS", //Description
"cancel", //Icon
7, //Time on screen
afterNotification //Callback function
);
}
}
GPS.prototype.showPosition = function(position)
{
gpsLatitude = position.coords.latitude;
gpsLongitude = position.coords.longitude;
gpsCallback();
}
GPS.prototype.getLatitude = function()
{
return gpsLatitude;
}
GPS.prototype.getLongitude = function()
{
return gpsLongitude;
}
GPS.prototype.showError = function(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
Lungo.Notification.error(
"Error", //Title
"Gebruiker staat geolocatie niet toe", //Description
"cancel", //Icon
7, //Time on screen
afterNotification //Callback function
);
break;
case error.POSITION_UNAVAILABLE:
Lungo.Notification.error(
"Error", //Title
"Locatie niet beschikbaar", //Description
"cancel", //Icon
7, //Time on screen
afterNotification //Callback function
);
break;
case error.TIMEOUT:
Lungo.Notification.error(
"Error", //Title
"Locatie timeout", //Description
"cancel", //Icon
7, //Time on screen
afterNotification //Callback function
);
break;
case error.UNKNOWN_ERROR:
Lungo.Notification.error(
"Error", //Title
"Unkown location error", //Description
"cancel", //Icon
7, //Time on screen
afterNotification //Callback function
);
break;
}
}
var GPS = new GPS();
The way I use the class:
var callback = function()
{
alert(GPS.getLongitude() + ", " + GPS.getLatitude());
}
GPS.setCallback(callback);
I,ve found my problem, I requested my location again in the getLattitude method. After removing this is works perfect.
Related
So for some reason I don't understand the purpose of mounted property. Hope someone could explain it further. Thanks in advance :)
bool get mounted => _element != null;
void getCurrentLocation() async {
locator.Location location = locator.Location();
location.getLocation().then(
(location) {
currentLocation = location;
},
);
GoogleMapController googleMapController = await _controller.future;
location.onLocationChanged.listen(
(newLoc) {
currentLocation = newLoc;
googleMapController.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
zoom: 13.5,
target: LatLng(
newLoc.latitude!,
newLoc.longitude!,
),
),
),
);
if (!mounted) {
return;
}
setState(() {});
// try {
// setState(() {});
// // } catch (e) {
// } on Exception catch (e) {
// _disposeController();
// }
},
);
}
im tryng to ad a zoom event on my map which transform my heatmap in marker. I found this code and tryinn to apply it on my map
var points = L.geoJson('1999to2022.geojson', {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {});
} });
map.on('zoomend', function() { var zoomlevel = map.getZoom();
if (zoomlevel <6){
if (map.hasLayer(points)) {
map.removeLayer(points);
} else {
console.log("no point layer active");
}
}
if (zoomlevel >= 7){
if (map.hasLayer(points)){
console.log("layer already added");
} else {
map.addLayer(points);
}
} });
I was wondering what I could be doing wrong and if this was the easiest way to display my popup.
Thanks!
I'd like to add both a TapGestureRecognizer and a LongPressGestureRecognizer to a TextSpan. Right now I can add either one, but not both.
I've looked into the GestureDetector class and wanted to wrap TextSpan with it, but the RichText element only accepts TextSpans and not Widgets.
This is what I have now:
TextSpan(
text: "some text",
recognizer: TapGestureRecognizer()
..onTap = () { print('tapped'); }
)
And I want to add ..onLongPress somewhere in that code.
At the end both gestures should work on the single text span.
It doesn't seem to be possible to add more than one GestureRecognizer to a TextSpan, but here is a workaround for your case with just the TapGestureRecognizer and using the onTapUp and onTapDown to detect a tap and to simulate a long tap, using a Timer:
TapGestureRecognizer _tapGestureRecognizer;
Timer _timer;
#override
void initState() {
super.initState();
_initRecognizer();
}
_initRecognizer() {
_tapGestureRecognizer = TapGestureRecognizer();
_tapGestureRecognizer.onTapUp = (_) {
if (_timer != null && _timer.isActive) {
print('Tap');
_timer.cancel();
}
};
_tapGestureRecognizer.onTapDown = (_) {
_timer = Timer(Duration(seconds: 1), () {
print('Long Tap');
});
};
}
#override
void dispose() {
if (_timer != null) {
_timer.cancel();
_timer = null;
}
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.all(16.0),
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: "This is some text.",
recognizer: _tapGestureRecognizer,
style: Theme.of(context).textTheme.title,
),
TextSpan(
text:
"Another piece of text. Another piece of text. Another piece of text. Another piece of text.",
style: Theme.of(context).textTheme.title,
),
],
),
),
),
);
}
You can use WidgetSpan to set into your span and detect TapGestureRecognizer and LongPressGestureRecognizer by GestureDetector
TextSpan(
children: <InlineSpan>[
TextSpan(text: 'Flutter is'),
WidgetSpan(
child: GestureDetector(
onTap: () {
},
onLongPress: () {
},
child: Text(' Hello World! '),
)
),
TextSpan(text: 'the best!'),
],
)
I combined TapGestureRecognizer and LongPressGestureRecognizer into a simple TapAndLongPressGestureRecognizer:
import 'package:flutter/gestures.dart';
///
/// A simple [GestureRecognizer] that combines [TapGestureRecognizer] and [LongPressGestureRecognizer]
/// It only supports two simple callbacks [onTap] and [onLongPress]
///
class TapAndLongPressGestureRecognizer extends PrimaryPointerGestureRecognizer {
/// Creates a gesture recognizer.
TapAndLongPressGestureRecognizer({
Duration? duration,
double? postAcceptSlopTolerance,
#Deprecated(
'Migrate to supportedDevices. '
'This feature was deprecated after v2.3.0-1.0.pre.',
)
PointerDeviceKind? kind,
Set<PointerDeviceKind>? supportedDevices,
Object? debugOwner,
}) : super(
deadline: duration ?? kLongPressTimeout,
postAcceptSlopTolerance: postAcceptSlopTolerance,
kind: kind,
supportedDevices: supportedDevices,
debugOwner: debugOwner,
);
bool _longPressAccepted = false;
// The buttons sent by `PointerDownEvent`. If a `PointerMoveEvent` comes with a
// different set of buttons, the gesture is canceled.
int? _initialButtons;
bool _sentTapDown = false;
bool _wonArenaForPrimaryPointer = false;
PointerDownEvent? _down;
PointerUpEvent? _up;
/// Called when a long press gesture by a primary button has been recognized.
///
GestureLongPressCallback? onLongPress;
/// A pointer has stopped contacting the screen, which is recognized as a tap
/// of a primary button.
///
/// This triggers on the up event, if the recognizer wins the arena with it
/// or has previously won, immediately following [onTapUp].
///
GestureTapCallback? onTap;
VelocityTracker? _velocityTracker;
#override
bool isPointerAllowed(PointerDownEvent event) {
switch (event.buttons) {
case kPrimaryButton:
if (onLongPress == null) {
return false;
}
break;
default:
return false;
}
return super.isPointerAllowed(event);
}
#override
void addAllowedPointer(PointerDownEvent event) {
assert(event != null);
if (state == GestureRecognizerState.ready) {
// If there is no result in the previous gesture arena,
// we ignore them and prepare to accept a new pointer.
if (_down != null && _up != null) {
assert(_down!.pointer == _up!.pointer);
_resetTap();
}
assert(_down == null && _up == null);
// `_down` must be assigned in this method instead of `handlePrimaryPointer`,
// because `acceptGesture` might be called before `handlePrimaryPointer`,
// which relies on `_down` to call `handleTapDown`.
_down = event;
}
if (_down != null) {
// This happens when this tap gesture has been rejected while the pointer
// is down (i.e. due to movement), when another allowed pointer is added,
// in which case all pointers are simply ignored. The `_down` being null
// means that _reset() has been called, since it is always set at the
// first allowed down event and will not be cleared except for reset(),
super.addAllowedPointer(event);
}
}
#override
void didExceedDeadline() {
// Exceeding the deadline puts the gesture in the accepted state.
resolve(GestureDisposition.accepted);
_longPressAccepted = true;
super.acceptGesture(primaryPointer!);
_checkLongPressStart();
}
#override
void handlePrimaryPointer(PointerEvent event) {
if (!event.synthesized) {
if (event is PointerDownEvent) {
_velocityTracker = VelocityTracker.withKind(event.kind);
_velocityTracker!.addPosition(event.timeStamp, event.localPosition);
}
if (event is PointerMoveEvent) {
assert(_velocityTracker != null);
_velocityTracker!.addPosition(event.timeStamp, event.localPosition);
}
}
if (event is PointerUpEvent) {
if (_longPressAccepted == true) {
_checkLongPressEnd(event);
_resetTap();
} else {
_up = event;
_checkTapUp();
}
_resetLongPress();
} else if (event is PointerCancelEvent) {
_resetLongPress();
if (_sentTapDown) {
_checkTapCancel(event, '');
}
_resetTap();
} else if (event is PointerDownEvent) {
_initialButtons = event.buttons;
_down = event;
_checkTapDown();
} else if (event is PointerMoveEvent) {
if (event.buttons != _initialButtons) {
resolve(GestureDisposition.rejected);
stopTrackingPointer(primaryPointer!);
}
}
}
void _checkTapUp() {
if (!_wonArenaForPrimaryPointer || _up == null) {
return;
}
assert(_up!.pointer == _down!.pointer);
switch (_down!.buttons) {
case kPrimaryButton:
if (onTap != null) {
invokeCallback<void>('onTap', onTap!);
}
break;
default:
}
_resetTap();
}
void _checkTapDown() {
if (_sentTapDown) {
return;
}
_sentTapDown = true;
}
void _checkTapCancel(PointerCancelEvent? event, String note) {}
void _resetTap() {
_sentTapDown = false;
_wonArenaForPrimaryPointer = false;
_up = null;
_down = null;
}
void _checkLongPressStart() {
switch (_initialButtons) {
case kPrimaryButton:
if (onLongPress != null) {
invokeCallback<void>('onLongPress', onLongPress!);
}
break;
default:
assert(false, 'Unhandled button $_initialButtons');
}
}
void _checkLongPressEnd(PointerEvent event) {
_velocityTracker = null;
}
void _resetLongPress() {
_longPressAccepted = false;
_initialButtons = null;
_velocityTracker = null;
}
#override
void resolve(GestureDisposition disposition) {
if (disposition == GestureDisposition.rejected) {
if (_longPressAccepted) {
// This can happen if the gesture has been canceled. For example when
// the buttons have changed.
_resetLongPress();
}
if (_wonArenaForPrimaryPointer && _sentTapDown) {
// This can happen if the gesture has been canceled. For example, when
// the pointer has exceeded the touch slop, the buttons have been changed,
// or if the recognizer is disposed.
_checkTapCancel(null, 'spontaneous');
_resetTap();
}
}
super.resolve(disposition);
}
#override
void acceptGesture(int pointer) {
if (pointer == primaryPointer && _down != null) {
_checkTapDown();
_wonArenaForPrimaryPointer = true;
_checkTapUp();
}
}
#override
void rejectGesture(int pointer) {
super.rejectGesture(pointer);
if (pointer == primaryPointer) {
// Another gesture won the arena.
assert(state != GestureRecognizerState.possible);
if (_sentTapDown) {
_checkTapCancel(null, 'forced');
}
_resetTap();
}
}
#override
String get debugDescription => 'tap or long press';
}
I am new for Titanium and creating my dummy app for iPhone.
I was using this code from a tutorial.
But am stuck in 'itemSelected' eventListener, looks like not working here.
I have tried by adding button, label and their click events even they are not working.
I am not getting my mistake here.
So please advice.
Thanks in advance.
My ApplicationWindow.js is..
//Application Window Component Constructor
function ApplicationWindow() {
//declare module dependencies
var MasterView = require('ui/listView_common/MasterView'),
DetailView = require('ui/listView_common/DetailView');
//create object instance
var self = Ti.UI.createWindow({
backgroundColor:'#fff'
});
//construct UI
var masterView = new MasterView(),
detailView = new DetailView();
//create master view container
var masterContainerWindow = Ti.UI.createWindow({title:'List View'});
masterContainerWindow.add(masterView);
//create detail view container
var detailContainerWindow = Ti.UI.createWindow({left:100,title:'Detail View'});
detailContainerWindow.add(detailView);
//create iOS specific NavGroup UI
var navGroup = Ti.UI.iPhone.createNavigationGroup({
window:masterContainerWindow
});
self.add(navGroup);
//add behavior for master view
masterView.addEventListener('itemSelected', function(e) {
alert("Alert");
navGroup.open(detailContainerWindow);
detailView.showArticle(e.link);
});
function refreshData() {
var file = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory+'jsonFiles/data.json');
var data = file.read().text;
var json = JSON.parse(data);
masterView.refreshDataTable(json);
}
// load data
refreshData();
return self;
};
module.exports = ApplicationWindow;
and my 'MasterView.js' is..
var createRow = function(item) {
var tablerow = Ti.UI.createTableViewRow({
height: 90,
link: item.link,
className: 'itemRow',
hasChild: true
});
var imageview = Ti.UI.createImageView({
image: item.image,
height: 55,
width: 68,
left: 5,
top: 3
});
var titleview = Ti.UI.createLabel({
text: item.title,
color: '#000',
font: {
fontSize: 16
},
left: 83,
right: 5,
top:5,
width:300
});
var dateview = Ti.UI.createLabel({
text: item.pubDate,
textAlign: 'center',
color: '#444',
font: {
fontSize: 12
},
height: 'auto',
width: 68,
left: 5,
top: 60
});
var nameview = Ti.UI.createLabel({
text: item.firstName +" " + item.lastName,
color: '#000',
font: {
fontSize: 14
},
left: 83,
right: 5,
top:30
});
var descriptionview = Ti.UI.createLabel({
text: item.description,
color: '#000',
font: {
fontSize: 12
},
left: 83,
top:50
});
tablerow.add(imageview);
tablerow.add(dateview);
tablerow.add(titleview);
tablerow.add(nameview);
tablerow.add(descriptionview);
return tablerow;
};
//Master View Component Constructor
function MasterView() {
var self = Ti.UI.createView({
backgroundColor:'#fff'
});
var table = Ti.UI.createTableView();
self.add(table);
table.addEventListener('click', function(e) {
self.fireEvent('itemSelected', { link: e.row.link });
});
self.refreshDataTable = function(data) {
if (Object.prototype.toString.apply(data) === '[object Array]') {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(createRow(data[i]));
}
table.setData(rows);
}
};
return self;
}
module.exports = MasterView;
DetailView.js
//Detail View Component Constructor
function DetailView() {
var self = Ti.UI.createView();
var webview = Ti.UI.createWebView();
self.add(webview);
self.showArticle = function(url) {
webview.url = url;
};
webview.addEventListener('load', function(e) {
self.fireEvent('articleLoaded');
});
return self;
}
module.exports = DetailView;
itemSelected is not a event type of window. That's why it's not working.
Try the click event and get apiName and perform your work based on the apiName.
Example:
windowNAme.addEventListener('click',function(e){
//when we click on button then we get id from this
getId=e.source.id;
if(getId=="mybutton")
{
perform your action here;
}
})
Try to use Titanium.App.addEventListener in your code as follows
//add behavior for master view
Ti.App.addEventListener('itemSelected', function(e) {
alert("Alert");
navGroup.open(detailContainerWindow);
detailView.showArticle(e.link);
});
and fire the event like
table.addEventListener('click', function(e) {
Ti.App.fireEvent('itemSelected', { link: e.row.link });
});
This will do the trick
You may also refer what is fireevent how do i use it
var button = Ti.UI.createButton({
left: 180,
top: 180,
width: 100,
hight: 30,
title: 'Go'
});
self.add(button);
button.addEventListener('click', function() {
var xhr = Ti.Network.createHTTPClient();
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
xhr.open("GET","http://erp.esworkplace.sap.com/sap/bc/srt/wsdl/bndg_DF52FF9E9AF025F18F0400145E5ADE89/wsdl11/allinone/ws_policy/document?sap-client=800");
xhr.setRequestHeader('Authorization', authstr);
xhr.setRequestHeader('Content-Type','text/xml');
xhr.setRequestHeader('Accept-Language','en');
alert('show');
xhr.onload = function(e)
{ try
{
//get the xml data and let it roll!
var doc = this.responseXML.documentElement;
// var items = doc.getElementsByTagName("atom:entry");
var items = doc.getElementsByTagName("wsdl:portType");
for(var c=0; c<items.length;c++){
var item = items.item(c);
alert(items.length);
var attributeEmployeeLeave = items.item(c).attributes.getNamedItem("name").nodeValue;
Ti.API.info(items.item(c).attributes.getNamedItem("name").nodeValue);
}
}
catch(E)
{
alert('error on xhr');
}
The response for the button addEventListener is not working
I dont know why!
Any one can advice me!
Simple Button Example
var button = Titanium.UI.createButton({ title: 'Hello' });
button.addEventListener('click',function(e) {
Titanium.API.info("You clicked the button"); });
Please change your button.addEventListener('click', function() { to button.addEventListener('click', function(e) {.