Draw rout in titanium Map - android

this is my code:
var win = Ti.UI.createView({
left : 0,
top : 0,
right : 0,
top : 0
});
Ti.UI.currentWindow.add(win);
var mapview = Titanium.Map.createView({
mapType : Titanium.Map.STANDARD_TYPE,
region : {
latitude : 0,
longitude : 0,
latitudeDelta : 1,
longitudeDelta : 1
},
animate : true,
regionFit : true,
userLocation : false,
});
win.add(mapview);
currenposition();
function drawrout(longitude, latitude) {
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
alert('HFL cannot get your current location');
return;
} else {
var xhr = Titanium.Network.createHTTPClient();
xhr.open('GET', "http://maps.googleapis.com/maps/api/directions/json?origin=" + latitude + ',' + longitude + "&destination=" + (latitude - 0.01) + ',' + (longitude - 0.01) + "&sensor=true");
xhr.onload = function() {
var xml = this.responseText;
var points = [];
// Bellow Variable have the step of the current location to destination Location. Using the Steps we going to create a route.
var position = JSON.parse(this.responseText).routes[0].legs[0].steps;
if (position[0] != null) {
points.push({
latitude : position[0].start_location.lat,
longitude : position[0].start_location.lng,
});
// Here we use the for loop to collect all the steps and push it to the array and use this array to form the route in android.
for (var i = 0; i < position.length; i++) {
points.push({
latitude : position[i].end_location.lat,
longitude : position[i].end_location.lng,
});
}
} else {
alert('no route');
}
var route = {
name : "india",
points : points,
color : "red",
width : 5
};
mapview.addRoute(route);
};
xhr.send();
}
});
}
function currenposition() {
Titanium.Geolocation.getCurrentPosition(function(e) {
if (e.error) {
alert('HFL cannot get your current location');
return;
} else {
var longitude = e.coords.longitude;
var latitude = e.coords.latitude;
mapview.region = {
latitude : latitude,
longitude : longitude,
latitudeDelta : 0.01,
longitudeDelta : 0.01
};
drawrout(longitude, latitude);
}
});
}
white this code I get sum line between two points but the rout is not god defined
like we can se it on the images the rout is defined by some points and a line between them. how can i get all points of the street so a can draw the line on top of the road?

For each step in XML response there is a polyline tag.
https://developers.google.com/maps/documentation/directions/intro#sample-response
You need to decode all polylines and add all the points of all the polylines in a point array.
http://thesundarnataraj.blogspot.it/2012/11/decoding-polylines-from-google-maps.html
Then you can use this array to make the route.

I solved my problem following this link:
https://archive.appcelerator.com/question/141002/plot-a-route-on-google-map-in-android#answer-245304

Related

Retrieve firebase data in the same order as its added

How do I retrieve the firebase list in the same order as it is added.
Looks like I’m getting them in a random order. I need to have them in order to draw my polyline in correct order.
List<LatLng> latLngList = new ArrayList<>();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot direction : snapshot.getChildren()) {
if (direction.getKey().equals(firebaseKey)) {
MyLatLng wantedDirection = direction.getValue(MyLatLng.class);
for (Waypoints waypoint : wantedDirection.getWaypoints().values()) {
double lat = waypoint.getLatitude();
double lang = waypoint.getLongitude();
LatLng latLng = new LatLng(lat, lang);
latLngList.add(latLng);
}
I want the JSON file to be in the same order as it the entries were added to the firebase list:
{
"timeStamp" : "2016-05-03 23:06:05",
"waypoints" : {
"-KGsf4xB_rZbsAMW4I2D" : {
"latitude" : 58.338713,
"longitude" : 11.90885
},
"-KGsf5M9YtZn6Yq22Kts" : {
"latitude" : 58.339218,
"longitude" : 11.910351
},
"-KGsf5qSV3X7cAIBtANF" : {
"latitude" : 58.340572,
"longitude" : 11.915417
},
"-KGsf6oww79POAY_e7kf" : {
"latitude" : 58.342271,
"longitude" : 11.921562
},
"-KGsf7JBaac5o7VMEZMh" : {
"latitude" : 58.344006,
"longitude" : 11.926909
},
"-KGsf7nGpMEgPA0j1rRl" : {
"latitude" : 58.345594,
"longitude" : 11.929302
},
"-KGsf8HjFtn7Dxpx-DpO" : {
"latitude" : 58.347846,
"longitude" : 11.931577
},
"-KGsf8ltvEBeqXE_me8Z" : {
"latitude" : 58.350397,
"longitude" : 11.932334
}
}
}
DataSnapshot.getChildren() will return the children in the order in which you've queried them from the database. If you're not specifying orderByChild() or orderByPriority() explicitly, that order will be by key, which means they will be iterated in the order they were inserted.
But for the waypoints, you are defining your own order:
for (Waypoints waypoint : wantedDirection.getWaypoints().values()
The values() of a Map are not going to be in a specific order afaik.
Update
To see the order in which the items are retrieved from Firebase, you can traverse the DataSnapshot:
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot direction: snapshot.getChildren()) {
DataSnapshot waypoints = direction.child("waypoints");
for (Waypoints waypoint: waypoints.getChildren()) {
double lat = waypoint.child("latitude").getValue(Double.class);
double lon = waypoint.child("longitude").getValue(Double.class);
LatLng latLng = new LatLng(lat, long);
latLngList.add(latLng);
}
}
Alternatively, you can look for a map that returns its entries in the order of its keys.
This worked for me:
for (Map.Entry<String, Waypoints> waypoint : wantedDirection.getWaypoints().entrySet()) {
String key = waypoint.getKey();
Waypoints value = waypoint.getValue();
double lat = value.getLatitude();
double lang = value.getLongitude();
LatLng latLng = new LatLng(lat, lang);
latLngRealList.add(latLng);
}

Cant find user location when apk installed on android phone

I have created an ionic angularjs ngCordova mobile app, wherein I have used ngCorodova geolocation plugin in order to get user location. when I am testing this on browser it works fine. but when same I [android-app.apk] I install on mobile app [obviously after checking "unknown sources" option]; I am not able to get the location. I see in app setting, permission is there to access location on mobile. Also, When event is trigerred it shows GPS symbol on top bar but it disappears.
Can anybody help me with this?
Below is the code for location in my controller.js
.directive('reverseGeocode', function ($cordovaGeolocation, $rootScope) {
return {
restrict: 'E',
template: '<div></div>',
link: function (scope, element, attrs) {
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
// console.log(angular.toJson($rootScope.lati) + " - " );
var request = new XMLHttpRequest();
var method = 'GET';
//var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true';
var async = true;
//alert(url);
//request.open(method, url, async);
//alert(angular.toJson(request.open(method, url, async)));
// var data = JSON.stringify(request.responseText);
// alert(JSON.stringify(request.responseText));
var latlng = new google.maps.LatLng(lati, longi);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//alert(results[1].address_components[1].long_name);
$rootScope.colony = results[1].address_components[1].long_name;
//alert(results[1].address_components[1].long_name);
//alert(results[1].address_components[1].long_name);
//alert(angular.toJson(results[1].address_components[1].long_name));
element.text(results[1].formatted_address);
} else {
element.text('Location not found');
}
} else {
element.text('Geocoder failed due to: ' + status);
}
});
}, function(err) {
// error
});
var watchOptions = {
frequency : 1000,
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
alert("abc >>" + lat);
var long = position.coords.longitude
});
watch.clearWatch();
// OR
$cordovaGeolocation.clearWatch(watch)
.then(function(result) {
// success
}, function (error) {
// error
});
},
replace: true
}
})
In html file I am using it as :
<h6>
User Colony: {{ colony }}
<reverse-geocode lat={{lati}} lng={{longi}}></reverse-geocode>
</h6>
<a href="#" ng-click="showStores(colony)" class="button button-block button-positive">
Browse Store
</a>
which triggeres the directive and find lat and long of user.
When testing on browser, it works perfectly but not on mobile itself.
In android it is super complicated to work with the GPS user, remember that often the geolocation we get is from the browser and not the GPS itself, and this varies a lot in the devices. For your help, I recommend installing cordova.plugins.diagnostic
function onDeviceReady() {
cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){
//alert("gps es : " + (enabled ? "enabled" : "disabled"));
}, function(error){
//alert("error: "+error);
});
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
if(!enabled){
alert("gps not actived");
}else{
navigator.geolocation.getCurrentPosition(onSuccess, onError, {enableHighAccuracy: true,timeout: 5000,maximumAge: 5000});
}
}, function(error){
console.log("The following error occurred: "+error);
});
}
Always trying to see if I can get a latitude and longitude and if that is not activated or not you can get, it sends a message to the user. I hope it helps you.

Adding the annotation on map is leading to app crash [Titanium]

I need to add around 1000 annotation on the map. Here is my code snippet:
nsNearby.markersSetup = function() {
var location = Alloy.Globals.playgroungLocationList.locations;
var annotationData = [];
for (var i = 0,
len = Alloy.Globals.playgroungLocationList.locations.length; i < len; i++) {
var mapAnnotation = nsNearby.mapModule.createAnnotation({
latitude : location[i].latitude,
longitude : location[i].longitude,
title : location[i].name,
subtitle : location[i].street
});
if (Titanium.Platform.osname === "android") {
mapAnnotation.pincolor = nsNearby.mapModule.ANNOTATION_BLUE;
} else {
mapAnnotation.pincolor = nsNearby.mapModule.ANNOTATION_PURPLE;
}
nsNearby.mapView1.region = {
latitude : location[i].latitude,
longitude : location[i].longitude,
latitudeDelta : 1,
longitudeDelta : 1
};
annotationData.push(mapAnnotation);
}
nsNearby.mapView1.setAnnotations(annotationData);
};
In iOS, it is working fine, but in Android, the app is crashing while adding the annotation.
If I put some specific numbers of annotation, it works.
It might be because of the extra load while placing the annotations. But, is there any way to achieve this?
Thanks in advance!

Remove annotations from Map in Titanium Appcelerator

I have made a Map based app using Titanium Appcelerator. I am showing the user's current location on the map. I also have a textbox where I am taking the user's desired location in order to show it on the map. For showing a particular place on the map I have used annotations and its working fine. The problem is that when the value of the textbox changes then another annotation is getting created on the map. What I want to do is, I want to clear the previous annotation before putting up a new annotation. My app.js file is depicted below:
app.js:
//create the window
var win1 = Titanium.UI.createWindow({
title:'Exercise Tracker',
backgroundColor: '#000'
});
//goto location label
var location_label = Titanium.UI.createLabel({
left:'10',
top:'20',
text:'Go to: ',
font:{fontSize:20}
})
//goto location textbox
var location_textbox= Titanium.UI.createTextField({
top: '15',
left: '85',
width: '300',
height: '50',
})
//go button
var btnGo=Ti.UI.createButton(
{
top:'15',
left:'420',
width:'50',
height:'50',
title:"Go"
})
//create our mapview
var mapview = Titanium.Map.createView({
top: 110,
height: 'auto',
width: 'auto',
mapType: Titanium.Map.STANDARD_TYPE,
region: {latitude: 51.50015,
longitude:-0.12623,
latitudeDelta:0.5,
longitudeDelta:0.5},
animate: true,
regionFit: true,
userLocation: true,
});
// to get values from both the textbox
btnGo.addEventListener('click', function (e){
//var addr=location_textbox.value;
var addr="";
addr = location_textbox.value;
annote(addr);
});
// to refrsh the page on click textbox
location_textbox.addEventListener('click', function (e){
});
//--------------------------annotations--------------------------------
//var addr = 'Howrah';
function annote(addr)
{
var addr_fw=addr;
Titanium.Geolocation.forwardGeocoder(addr,function(evt) {
var objLocationAnnotation = Titanium.Map.createAnnotation({
latitude: evt.latitude,
longitude: evt.longitude,
title: addr_fw
});
mapview.addAnnotation(objLocationAnnotation);
});
}
//--------------------------annotations--------------------------------
//add the map to the window
win1.add(mapview);
//set the distance filter
Titanium.Geolocation.distanceFilter = 10;
Titanium.Geolocation.getCurrentPosition(function(e)
{
if (e.error)
{
//if mapping location doesn't work, show an alert
alert('Sorry, but it seems geo location is not available on your device!');
return;
}
//get the properties from Titanium.GeoLocation
var longitude = e.coords.longitude;
var latitude = e.coords.latitude;
var altitude = e.coords.altitude;
var heading = e.coords.heading;
var accuracy = e.coords.accuracy;
var speed = e.coords.speed;
var timestamp = e.coords.timestamp;
var altitudeAccuracy = e.coords.altitudeAccuracy;
//apply the lat and lon properties to our mapview
mapview.region = {latitude: latitude,
longitude: longitude,
latitudeDelta:0.5,
longitudeDelta:0.5
};
});
//finally, open the window
win1.open();
//adding display properties to the main window
win1.add(location_label);
win1.add(location_textbox);
win1.add(btnGo);
Use mapView.removeAnnotation String/Titanium.Map.Annotation annotation
it Removes an existing annotation from the map.
read the documentation for further details from here.
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Map.View-method-removeAnnotation
Change
mapview.addAnnotation(objLocationAnnotation);
to
mapview.annotations = [objLocationAnnotation];
That will clear all the annotations on the mapview and set them to a new array of the one new annotation.

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