Dart: How do I count items in 2d list - android

I'm new to Dart/Flutter.
I don't know how to count items from a 2d list.
List<List<bool>> a = [
[true, true, false, false],
[true, false, false, true]
];
I want to count true in this list, but in vertically.
So I want a result like this:
result = [2, 1, 0, 1]
Thank you!

you can use the spread operator to assign length of inner list to a resultant array like this
void main() {
const a = [
[true, true, false],
[true, false, false, true, true]
];
var result = [];
for(var element in a) {
var count = 0;
for (var el in element) {
if (el) {
count += 1;
}
}
result = [...?result,count];
}
print(result);
}
try this code in Dartpad

extension on List<bool> {
List<int> addIfTrue(List<int> counter) {
if (counter.length == length && counter.isNotEmpty) {
var i = 0;
forEach((e) => e ? counter[i++]++ : i++);
return counter;
}
return [];
}
}
void main() {
var a = [
[true, true, false, false],
[true, false, false, true]
];
var n = a[0].length;
var z = a.fold<List<int>>(List.filled(n, 0), (prev, e) => e.addIfTrue(prev));
print(z);
}
Result:
[2, 1, 0, 1]

Related

React native listview does not show all the rows

I have a questionnaire application which works fine on Android. However on iOS, the ListView never shows all the questions. Of the 11 questions in the questionnaire. only about 2 or 2.5 of them are rendered. A small amount of scrolling does seem to happen based on the size off the emulator window. I have tried all the suggestion posted including:
- setting the height of the ListView item using Dimensions
- setting flex:1 up the container hierarchy.
But nothing seems to work.
I am posting a much abridged and modified version of the code that uses NativeBase's RadionButton. My original code uses my own home-brewed radio buttons, but all of them have the same problem. I would appreciate any help I can get on this problem. Thanks in advance.
Here is my code:
import React, { Component } from 'react';
import {
Alert,
StyleSheet,
// Text,
TextInput,
View,
ListView,
TouchableHighlight,
Dimensions,
} from 'react-native';
import Svg,{
Rect,
} from 'react-native-svg';
import { Actions } from 'react-native-router-flux';
import realm from './realm';
import Utils from './Utils';
import moment from 'moment';
import { Container, Content, InputGroup, Input,
List, ListItem, Text, Radio } from 'native-base';
require('Dimensions');
const windowDims = Dimensions.get('window');
///////////////////////////////////////////////////////////////////////////////
const WhenSymptom = 0;
const FrequencySymptom = 1;
const FeelingSymptom = 2;
const YesNoSymptom = 3;
const ValueSymptom = 4;
global.junk = "hello";
var SymptomValues = new Array
(
// WhenSymptom
[ "none", "only after inactivity", "mostly AM", "AM and PM", "all the time" ],
// FrequencySymptom
[ "None", "Less than usual", "Usual", "More than usual", "Very bothersome" ],
// FeelingSymptom
[ "Great", "Fair", "So-so", "Poor", "Terrible" ],
// YesNoSymptom
[ "No", "", "", "", "Yes" ],
// ValueSymptom
[]
);
// var questions = new Array
global.questions = new Array
(
{ rowIndex: 0,
chartTitle: "Tremors",
answer: 0},
{ rowIndex: 1,
chartTitle: "Speech-slurring",
answer: 1},
{ rowIndex: 2,
chartTitle: "Feeling-stuck",
answer: 2},
{ rowIndex: 3,
chartTitle: "Instability",
answer: 3},
{ rowIndex: 4,
chartTitle: "Anxiety",
answer: 4},
{ rowIndex: 5,
chartTitle: "# of steps",
answer: 1},
{ rowIndex: 6,
chartTitle: "Pain or aches",
answer: 3},
{ rowIndex: 7,
chartTitle: "Day drowsiness",
answer: 2},
{ rowIndex: 8,
chartTitle: "Urinary urgency",
answer: 1},
{ rowIndex: 9,
chartTitle: "Constipation",
answer: 0},
{ rowIndex: 10,
chartTitle: "Overall feeling",
answer: 2}
);
var colors = new Array( "green", "#dbdb70", "yellow", "orange", "red" );
var styles = StyleSheet.create({
list: {
flexDirection: 'column',
flex:1,
//height: windowDims.height-30,
marginTop: 52,
},
questionText: {
flex:1,
fontSize: 14,
// color: 'white',
color: 'black',
alignSelf: 'flex-start'
},
});
var junk = 0;
// const mySaveAction = () => console.log('Back From the Questions page ');
///////////////////////////////////////////////////////////////////////////////
export default class QuestionsPage extends Component {
constructor(props){
super(props);
console.log("numToPop: " + this.props.numToPop);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
//rowHasChanged: (r1, r2) => true
});
// if it is a new panel, set all the answers to -1
let answersIn = new Array(questions.length);
if (this.props.panel == null) {
for (let i in questions) {
answersIn[i] = -1;
questions[i].answer = -1;
}
}
else {
answersIn = this.props.panel.symptoms.split(",");
for (let i in questions) {
questions[i].answer = answersIn[i];
}
}
this.state = {
ds: questions,
dataSource:ds,
editAllowed: 0,
initialAnswers: answersIn,
behavior: 'position'
// there is three ways to adjust (position , height , padding )
}
}
///////////////////////////////////////////////////////////////////////////////
componentDidMount(){
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.state.ds),
});
// When we come in here with newPanel == 1, the route was
// MenuPage => QuestionsPage; so cancel should just be
// Actions.pop(). If newPanel == 0, , the route was
// MenuPage => Calendar => QuestionsPage; so cancel should call Actions.pop(2)
Actions.refresh({ onRight: () => { this._saveButtonPressed(); },
onBack: () => { this._cancelButtonPressed(); },
title: (this.props.panel == null ?
"New panel" :
(" Panel of " +
Utils.readableDate(this.props.panel.panelDate)))
});
}
///////////////////////////////////////////////////////////////////////////////
_saveButtonPressed() {
var finalAnswers = new Array(questions.length);
var panelChanged = 0;
var dateString;
for (let i=0; i<finalAnswers.length; i++) {
finalAnswers[i] = questions[i].answer;
if (finalAnswers[i] != this.state.initialAnswers[i])
panelChanged = 1;
}
var symptoms = "" + finalAnswers[0];
for (let i=1; i<finalAnswers.length; i++) {
symptoms = (symptoms + "," + finalAnswers[i]);
}
console.log("_saveButtonPressed panelChanged: " + panelChanged);
if (this.props.panel == null) {
if (panelChanged) {
let myPanelKey = Utils.newPanelKey();
this._updateDB(myPanelKey, symptoms);
}
Actions.pop();
}
else {
if (panelChanged) {
this._updateDB(this.props.panel.panelDate, symptoms);
}
// Kluge:
this._returnFromScreen();
}
}
///////////////////////////////////////////////////////////////////////////////
_updateDB(myPanelDate, symptoms) {
console.log("_updateDB dt: " + moment(myPanelDate).toString() +
" symptoms: " + symptoms);
// var dateString = Utils._myISOString(myPanelDate);
realm.write(() => {
realm.create('Symptoms', {panelDate: myPanelDate, symptoms: symptoms}, true);
});
console.log("Trace");
let after = realm.objects('Symptoms');
for (let i=0; i<after.length; i++) {
console.log("panelDate: " + moment(after[i].panelDate).toString() +
" (" + after[i].panelDate + " )" +
"; symptoms: " + after[i].symptoms);
}
}
///////////////////////////////////////////////////////////////////////////////
_returnFromScreen() {
if (this.props.numToPop == 1)
Actions.pop();
else
Actions.pop({popNum: 2});
}
///////////////////////////////////////////////////////////////////////////////
_cancelButtonPressed() {
console.log("_cancelButtonPressed in QuestionsPage numToPop: " +
this.props.numToPop);
this._returnFromScreen();
}
///////////////////////////////////////////////////////////////////////////////
_rowPressed(rowData){
console.log("In _rowPressed");
}
///////////////////////////////////////////////////////////////////////////////
_buttonPressed(rowIndex, value, forceEdit = 0){
// console.log("In _buttonPressed " + rowIndex + " " + value);
let newDs = this.state.ds.slice();
newDs[rowIndex] = {
...this.state.ds[rowIndex],
answer: value,
};
// This is absolutely essential to do!!!!!
questions[rowIndex].answer = value;
this.setState({
dataSource:this.state.dataSource.cloneWithRows(newDs),
})
// this.forceUpdate();
// console.log("answers: " + this.state.answers);
}
///////////////////////////////////////////////////////////////////////////////
_renderButton(rowIndex, column){
return (
<ListItem>
<Radio selected={this.state.ds[rowIndex].answer == column ? true : false} />
<Text>{SymptomValues[0][column]}</Text>
</ListItem>
);
}
///////////////////////////////////////////////////////////////////////////////
_renderRow(rowData){
// console.log("renderRow " + this.state.ds[rowData.rowIndex].answer);
return (
<View style={styles.list}>
<Text style={styles.questionText}>Question {rowData.rowIndex+1}.</Text>
<Container>
<Content>
<List>
{ this._renderButton(rowData.rowIndex, 0) }
{ this._renderButton(rowData.rowIndex, 1) }
{ this._renderButton(rowData.rowIndex, 2) }
{ this._renderButton(rowData.rowIndex, 3) }
{ this._renderButton(rowData.rowIndex, 4) }
</List>
</Content>
</Container>
</View>
);
}
///////////////////////////////////////////////////////////////////////////////
render(){
// console.log("render");
return (
<ListView style={styles.list}
dataSource = {this.state.dataSource}
renderRow = {this._renderRow.bind(this)}>
</ListView>
);
}
}
module.exports = QuestionsPage;
// Util.js
import moment from 'moment';
let Utils = {
// toISOString returns (YYYY-MM-DDTHH:mm:ss.sssZ
newPanelKey: function() {
let myPanelDate = moment();
myPanelDate.milliseconds(0);
myPanelDate.seconds(0);
myPanelDate.minutes(0);
return myPanelDate.valueOf();
},
readableDate: function(utc) {
return moment(utc).format("MMM D, YYYY#ha");
},
readableDateNoTime: function(utc) {
return moment(utc).format("MMM D, YYYY");
},
shortDate: function(utc) {
let mom = moment(utc);
let date = mom.format("DDMMM:hha");
return date.substring(0,date.length-1);
}
}
module.exports = Utils;

How to implement jQuery mobile swipe/shake in place of mouse swiping?

I have managed to build a simple jQuery flash card game following an online tutorial, resulting in this code:
var eng2fr = {
from: null,
to: null,
suggester: {
i: 0,
words: [
[ "beer", "binouze" ],
[ "another beer", "une autre bière" ],
[ "crazy", "fou" ],
[ "What the heck?!", "c'est quoi ce délire" ],
[ "whatever", "n'importe quoi"]
],
next: function(){
return this.words[ ( this.i++ ) % this.words.length ];
}
},
init: function(el) {
this.bindSwipe( $( "#display" ) );
this.from = $( "#from" );
this.to = $( "#to" );
Events.listen( "card_next", $.proxy( this.next, this ) );
Events.listen( "card_flip", $.proxy( this.flip, this ) );
// Begin!
this.next();
},
next: function() {
var to = this.to,
from = this.from,
next = this.suggester.next(),
_this = this;
to.text( next[ 0 ] );
to.addClass( "push in current" );
from.addClass( "push out" ).one( "webkitAnimationEnd", function() {
from.text( next[ 1 ] );
from.removeClass( "current push out" );
to.removeClass( "push in" );
_this.from = to;
_this.to = from;
});
},
flip: function() {
var to = this.to,
from = this.from,
_this = this;
to.addClass( "flip in current" );
from.addClass( "flip out" ).one( "webkitAnimationEnd", function() {
from.removeClass( "current flip out" );
to.removeClass( "flip in" );
_this.from = to;
_this.to = from;
});
},
bindSwipe: function( el ) {
this.xStart = null;
this.downEvent = 'ontouchstart' in document.documentElement && navigator.appVersion.indexOf( 'iPhone OS ' ) > -1 ? 'touchstart' : 'mousedown';
this.upEvent = 'ontouchend' in document.documentElement && navigator.appVersion.indexOf( 'iPhone OS ' ) > -1 ? 'touchend' : 'mouseup';
var _this = this;
el.bind({
"touchstart mousedown": function( e ) {
if( e.type !== _this.downEvent ) return;
e.preventDefault();
_this.xStart = e.pageX && e.pageX > 0 ? e.pageX : e.originalEvent.changedTouches[ 0 ].pageX;
},
"touchend mouseup": function( e ) {
if( e.type !== _this.upEvent ) return;
var newX = e.pageX && e.pageX > 0 ? e.pageX : e.originalEvent.changedTouches[ 0 ].pageX;
var diff = newX - _this.xStart;
if( Math.abs( diff ) > 20) {
if( diff > 0 ){
Events.trigger( "card_previous", {} );
} else {
Events.trigger( "card_next", {} );
}
} else {
Events.trigger( "card_flip", {} );
}
},
"touchmove": function( e ) {
e.preventDefault();
}
});
}
};
As you can probably see, this code relies on mouse events for flipping and browsing through cards. I'm looking to implement jQuery mobile swipe/tap functions in place of these and I was wondering if someone could help me with that or at least point me in the right direction.
Also, I'm wondering if there is a simple way to detect a shake event and use this to select a random "card" / word pair?

textField in listView

This is my first question in this community that refers to the API of titanium studio. I explain: I'm trying to put a textField inside a listView an item, but when compiled and when to focus on the text area will not let me write and when it does it does in other type of listView.
I hope you can help with this
var win = Ti.UI.createWindow({
backgroundColor:'#FFF'
});
var plainTemplate = {
childTemplates: [
{
type: 'Ti.UI.Label',
bindId: 'title',
properties: {
width: '100%',
height: 30,
left: 0,
top:0
}
},
{
type: 'Ti.UI.TextArea',
bindId: 'campo',
properties: {
top:60,
width: '70%',
left:10,
height:40
}
}
],
events: {click: check }
};
var listView = Ti.UI.createListView({
templates: { 'uncheck': plainTemplate},
defaultItemTemplate: 'uncheck'
});
var data = [];
for (var i = 0; i < 20; i++) {
data.push({
title : { text: 'row' + i },
properties : {
itemId: 'row' + i,
accessoryType: Ti.UI.LIST_ACCESSORY_TYPE_NONE,
}
});
}
var section = Ti.UI.createListSection();
section.setItems(data);
listView.sections = [section];
function check() {
alert('estas aqui!!');
}
win.add(listView);
win.open();
Have you tried out to remove the top-Property in UITextArea of 60px? That could be the reason, why your textarea is at another position as you've expected:
{
type: 'Ti.UI.TextArea',
bindId: 'campo',
properties: {
// top: 60 <--- remove that line
width: '70%',
left:10,
height:40
}
}
I haven't tested your whole code, but i added this value for a top property to a ListView in an App where i am working on and it ended in an similar behaviour as you wrote.

Sencha Touch 2 - How to run a function after a view is loaded?

I have a view in Sencha Touch which I populate via the initialize function. Here's the code:
Ext.define("Pycsell.view.Home", {
extend: "Ext.form.Panel",
requires: "Ext.form.FieldSet",
alias: "widget.homepage",
config:{
scrollable: false,
cls: 'splash_screen',
layout: 'vbox'
},
initialize: function () {
this.callParent(arguments);
var fb_login = {
xtype: 'button',
cls: 'fb_login_button'
};
var tradreg = {
xtype: 'button',
cls: 'tradreg_button'
};
var tradlog = {
xtype: 'button',
cls: 'tradlog_button'
};
var logo_container = Ext.create('Ext.Panel', {
cls: 'logo_container',
width: '90%',
flex: 4,
});
var button_container = Ext.create('Ext.Panel', {
cls: 'splash_content',
items: [fb_login, tradreg, tradlog],
flex: 2,
});
this.add([
logo_container,
button_container
]);
this.setButtonSizes();
},//End init
setButtonSizes: function() {
console.log('Width is:' + $('.fb_login_button').width());
console.log('Old height is:' + $('.fb_login_button').height());
var height = $('.fb_login_button').width()*0.29;
$('.fb_login_button').height(height);
console.log('New height is:' + $('.fb_login_button').height());
}
});
Now, the setButtonSizes function does fire, but all the values are null, leading me to believe that the items haven't actually been initialized at the time it's called. How would I go about doing this properly so that the values are actually set? Thanks in advance.
This can be notoriously tricky to get right. The problem is that your function is probably being called before the component is rendered. I haven't done any work with Sencha Touch 2, but it looks like using the painted event should help. Something like this:
Ext.define("Pycsell.view.Home", {
extend: "Ext.form.Panel",
requires: "Ext.form.FieldSet",
alias: "widget.homepage",
config:{
scrollable: false,
cls: 'splash_screen',
layout: 'vbox'
},
initialize: function () {
this.callParent(arguments);
var fb_login = {
xtype: 'button',
cls: 'fb_login_button'
};
var tradreg = {
xtype: 'button',
cls: 'tradreg_button'
};
var tradlog = {
xtype: 'button',
cls: 'tradlog_button'
};
var logo_container = Ext.create('Ext.Panel', {
cls: 'logo_container',
width: '90%',
flex: 4,
});
var button_container = Ext.create('Ext.Panel', {
cls: 'splash_content',
items: [fb_login, tradreg, tradlog],
flex: 2,
});
this.add([
logo_container,
button_container
]);
/* Attaches a listener to the component that will be fired after the
component is rendered or shown. */
this.on('painted', this.setButtonSizes);
},//End init
setButtonSizes: function() {
console.log('Width is:' + $('.fb_login_button').width());
console.log('Old height is:' + $('.fb_login_button').height());
var height = $('.fb_login_button').width()*0.29;
$('.fb_login_button').height(height);
console.log('New height is:' + $('.fb_login_button').height());
}
});
Depending on quite what you're trying to accomplish, this may fire the event too many times (looks like it fires every time the component is shown too). So you may have to adjust setButtonSizes to compensate.

Android Geolocation Null in Titanium

I can't get geolocations in the emulator or on a physical phone.
I'm using Titanium SDK 1.6.2, ADK 2.2.
I've followed the approaches used here to no avail.
What am I missing? Thanks in advance.
Error:
Says that e.coords is null when doing this assignment. f_lng = e.coords.longitude;
Code:
function get_geolocation() {
try {
Ti.Geolocation.preferredProvider = 'gps';
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
if( Titanium.Geolocation.locationServicesEnabled === false ) {
throw('Your device has GPS turned off. Please turn it on.');
}
var f_lat, f_lng;
Titanium.Geolocation.getCurrentPosition(function(e) {
if( ! e.success || e.error ) {
alert("Unable to get your location.");
}
f_lng = e.coords.longitude;
f_lat = e.coords.latitude;
});
return {
's_status': 'success',
'f_lat': f_lat,
'f_lng': f_lng
};
} catch( s_error ) {
return {
's_status': 'error',
's_message': s_error
};
}
}
Ti.App.GeoApp = {};
Ti.Geolocation.preferredProvider = Titanium.Geolocation.PROVIDER_GPS;
Ti.Geolocation.purpose = "testing";
Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;
Titanium.Geolocation.distanceFilter = 10;
if( Titanium.Geolocation.locationServicesEnabled === false ) {
Ti.API.debug('Your device has GPS turned off. Please turn it on.');
}
function updatePosition(e) {
if( ! e.success || e.error ) {
alert("Unable to get your location.");
Ti.API.debug(JSON.stringify(e));
Ti.API.debug(e);
return;
}
Ti.App.fireEvent("app:got.location", {
"coords" : e.coords
});
};
Ti.App.addEventListener("app:got.location", function(d) {
Ti.App.GeoApp.f_lng = d.longitude;
Ti.App.GeoApp.f_lat = d.latitude;
Ti.API.debug(JSON.stringify(d));
Ti.Geolocation.removeEventListener('location', updatePosition);
alert(JSON.stringify(d));
});
var tabGroup = Titanium.UI.createTabGroup();
//
// create base UI tab and root window
//
var window = Titanium.UI.createWindow({
backgroundColor:'#fff',
barColor:'#003333',
});
var tab1 = Titanium.UI.createTab({
icon:'KS_nav_views.png',
title:'Tab 1',
window:window
});
tabGroup.open();
Titanium.Geolocation.getCurrentPosition( updatePosition );
Titanium.Geolocation.addEventListener( 'location', updatePosition );
see more details here http://blog.clearlyinnovative.com/post/5384374513/titanium-appcelerator-quickie-get-location-android
Piggy-backing off of Aaron's answer, here is what worked for me on IPhone Simulator, IPhone, and Android phone (not Android simulator). Keep in mind that I use redux so the code will be a little different.
var path = Ti.Platform.name == 'android' ? Ti.Filesystem.resourcesDirectory : "../../";
var map = {
top: 0,
bottom: 0,
latitude: 0,
longitude: 0,
latitudeDelta: 0.1,
longitudeDelta: 0.1,
display: "map",
init: function (annotations, latitude, longitude, top, bottom, delta) {
if (top)
map.top = top;
if (bottom)
map.bottom = bottom;
if (delta) {
map.latitudeDelta = delta;
map.longitudeDelta = delta;
}
map.createMap(annotations, latitude, longitude);
map.createOptions();
map.getLocation();
},
createMap: function (annotations, latitude, longitude) {
map.mapView = Ti.Map.createView({
mapType: Ti.Map.STANDARD_TYPE, animate: true, regionFit: false, userLocation: true,
region: { latitude: latitude, longitude: longitude, latitudeDelta: map.latitudeDelta, longitudeDelta: map.longitudeDelta },
annotations: annotations, bottom: map.bottom, top: map.top, borderWidth: 1
});
if (!isAndroid) {
map.mapView.addAnnotation(annotations[0]);
}
map.mapView.selectAnnotation(annotations[0]);
win.add(map.mapView);
},
createOptions: function () {
//map/satellite displays.
var mapDisplay = new ImageView({ image: path + 'images/map/satellite-view.png', width: 70, height: 49, zIndex: 2, top: map.top + 5, right: 5 });
mapDisplay.addEventListener('click', function () {
if (map.display == "map") {
map.mapView.setMapType(Titanium.Map.SATELLITE_TYPE);
mapDisplay.image = path + "images/map/map-view.png";
map.display = "satellite";
}
else {
map.mapView.setMapType(Titanium.Map.STANDARD_TYPE);
mapDisplay.image = path + "images/map/satellite-view.png";
map.display = "map";
}
});
win.add(mapDisplay);
//crosshairs.
if(Ti.Geolocation.locationServicesEnabled) {
var centerDisplay = new ImageView({ image: path + 'images/map/crosshairs.png', width: 49, height: 49, zIndex: 2, top: map.top + 5, right: 80 });
centerDisplay.addEventListener('click', function () {
if(map.latitude != 0 && map.longitude != 0) {
info("setting user location to " + map.latitude + " / " + map.longitude);
//center map.
var userLocation = {
latitude: map.latitude,
longitude: map.longitude,
latitudeDelta: map.latitudeDelta,
longitudeDelta: map.longitudeDelta,
animate: true
};
map.mapView.setLocation(userLocation);
}
});
win.add(centerDisplay);
}
},
createAnnotation: function (title, subtitle, latitude, longitude, isLocation, addToMap) {
var mapAnnotation = Ti.Map.createAnnotation({
latitude: latitude, longitude: longitude,
title: title,
subtitle: subtitle,
animate: true
});
if (isAndroid) {
mapAnnotation.pinImage = path + (isLocation ? "images/map/blue-pin.png" : "images/map/purple-pin.png");
}
else {
mapAnnotation.pincolor = isLocation ? Ti.Map.ANNOTATION_PURPLE : Ti.Map.ANNOTATION_RED;
}
if (addToMap)
map.mapView.addAnnotation(mapAnnotation);
return mapAnnotation;
},
updateAnnotation: function (mapAnnotation, title, subtitle, latitude, longitude, isLocation) {
if (mapAnnotation) {
map.mapView.removeAnnotation(mapAnnotation);
mapAnnotation = map.createAnnotation(title, subtitle, latitude, longitude, isLocation);
map.mapView.addAnnotation(mapAnnotation);
map.mapView.selectAnnotation(mapAnnotation);
}
},
addAnnotation: function (mapAnnotation) {
map.mapView.addAnnotation(mapAnnotation);
},
removeAnnotation: function (mapAnnotation) {
map.mapView.removeAnnotation(mapAnnotation);
},
selectAnnotation: function (mapAnnotation) {
map.mapView.selectAnnotation(mapAnnotation);
},
createRoute: function (name, points) {
var route = {
name: name, points: points, color: "#7c74d4", width: 4
};
map.mapView.addRoute(route);
setTimeout(function () { map.mapView.regionFit = true; }, 700);
},
getLocation: function() {
Ti.Geolocation.preferredProvider = Ti.Geolocation.PROVIDER_GPS;
Ti.Geolocation.purpose = "testing";
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
Ti.Geolocation.distanceFilter = 10;
if(!Ti.Geolocation.locationServicesEnabled) {
//alert('Your device has GPS turned off. Please turn it on.');
return;
}
function updatePosition(e) {
if(!e.success || e.error) {
info("Unable to get your location - " + e.error);
return;
}
info(JSON.stringify(e.coords));
map.latitude = e.coords.latitude;
map.longitude = e.coords.longitude;
Ti.Geolocation.removeEventListener('location', updatePosition);
};
Ti.Geolocation.getCurrentPosition(updatePosition);
Ti.Geolocation.addEventListener('location', updatePosition);
}
};
Have you tried setting a timeout to make sure the e.coords is set before you use it, it has been suggested as a temporary fix?
setTimeout(function() {
return e.coords
}, 1000);

Categories

Resources