How to add locations and distances to a custom layout android - android

I am making an android app that will list specific places that are not on google places. I have all the latitude and longitudes and place names and they will not be changing. I can display them in my custom list and it works fine the problem is I want to sort them all by distance from your(the users) location and display the distance next to them.
I have tried lots of different ways but have become a bit stuck. I would like to say that I am new to programming and sort of stumbling my way through this app, If anyone could help it would be really appreciated.
So the question im asking is how can/should I sort locations by distance so I can add them to my custom list.
// create array to hold place names to be looped through later
String[] placenames = { "place1", "place2",
"place3", "place4" };
// // create arrays to hold all the latitudes and longitudes
double[] latArray = new double[] { 51.39649, 51.659775, 51.585433,
51.659775 };
double[] lngArray = new double[] { 0.836523, 0.539901, 0.555385,
0.539901, };
// hard code my location for test purposes only
Location MyLocation = new Location("My location");
MyLocation.setLatitude(51.659775);
MyLocation.setLongitude(0.539901);
for (int i = 0; i < placenames.length;) {
// Place location object
Location PlaceName = new Location(placenames[i]);
PlaceName.setLatitude(latArray[i]);
PlaceName.setLongitude(lngArray[i]);
i++;
// calculate distance in meters
float distanceInMeters = PlaceName.distanceTo(MyLocation);
// convert to double
double DistanceInMiles = distanceInMeters * 0.000621371;
dimint = (int) DistanceInMiles;
// format numbers to two decimal places
DecimalFormat df = new DecimalFormat("#.##");
dim = df.format(DistanceInMiles);
//make treemap and then sortedmap to sort places by distance
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
SortedMap<Integer, String> treemapsorted = new TreeMap<Integer,String>();
treemap.put(dimint, PlaceName.getProvider());
treemapsorted = treemap.subMap(0, 5);
// Toast for test purpose to see if sort is working
Toast tst = Toast.makeText(this, treemapsorted.entrySet()
.toString(), Toast.LENGTH_SHORT);
tst.show();
CustomList place_data[] = new CustomList[] {
// This is the problem part
new CustomList(R.drawable.picture1, treemapsorted.get(dimint)),
};
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView1);
listView1.setAdapter(adapter);
;
}

I just reviewed your code and found lots of problems:
Use i++ in your for loop statement instead of in the loop body, like this:
for (int i = 0; i < placenames.length; i++) {
}
You calculate the distance in miles, cast this to int (I would use Math.round() here) and then create a string with DecimalFormat which you don't use.
You create a TreeMap in every loop iteration. Move the creation in front of the loop and add items to it in the loop body.
TreeMap is not the right class for this task. I tested your code and the Map contained only 3 items after the loop. The reason is, that a TreeMap contains key value pairs, where the key has to be unique. Adding an element with a key (distance in your case), which is already in the map, results in overwriting that element. So instead of a TreeMap I recommend using an ArrayList. You need to create a class with all the variables you need, like distance and place name. This class needs to implement the interface Comparable<Class>. You will then have to implement the method public int compareTo(T other) in which you compare the distance with the distance of the other object. Then you can sort the ArrayList using Collections.sort(arrayList). In the for loop body you should add items to that ArrayList, then sort it, then iterate over the ArrayList items and add them to your ListView.

Related

Looping with while loop while fetching records from database is not working properly

Im trying to iterate two arrays simultaneously as follows,
First if countriesIterator has got next element, domain Iterator will be looped.
CountryIterator has got two elements and domain iterator might contain n elements.
when Im looping the domainIterator, Im populating an arraylist with values that I have looped.
and when the loop reaches the country iterator, Im putting the arraylist within a hashmap.
Iterator<String> domainIterator = selectedDomains.iterator();
Iterator<String> countriesIterator = selectedCountries.iterator();
filteredComplianceCount = new ArrayList<Integer>();
inProgressComplianceCount = new ArrayList<Integer>();
delayedComplianceCount = new ArrayList<Integer>();
nonComplianceCount = new ArrayList<Integer>();
//Looping Countries
while (countriesIterator.hasNext()) {
String countryKey = countriesIterator.next();
Country country = aparjithaDb.getCountryId(countryKey);
//Looping Domains
while (domainIterator.hasNext()) {
Domain domain = aparjithaDb.getDomain(domainIterator.next());
int domainId = domain.getDomainId();
int countryId = country.getCountryId();
//fetch datas from db based on country and domain id/
List<ChartData> allChartCDCounts = db.getAllChartCDCounts(countryId, domainId);
//iterate the list to get the count values
for (ChartData al : allChartCDCounts) {
int complied_count = al.getComplied_count();
int delayed_compliance_count = al.getDelayed_compliance_count();
int not_complied_count = al.getNot_complied_count();
int inprogress_compliance_count = al.getInprogress_compliance_count();
//add the count values to an arraylist
filteredComplianceCount.add(complied_count);
delayedComplianceCount.add(delayed_compliance_count);
inProgressComplianceCount.add(inprogress_compliance_count);
nonComplianceCount.add(not_complied_count);
}
}
//put the arraylist with in hashmap
compMap.put(countryKey, filteredComplianceCount);
delayedCompMap.put(countryKey, delayedComplianceCount);
inProgMap.put(countryKey, inProgressComplianceCount);
nonCompMap.put(countryKey, nonComplianceCount);
}
The problem with my code is that, the key of hashmap remains unique (The keys are two different country names after adding values) but the values remains the same for both keys. The domain Iterator is being invoked only once but it should have been invoked twice because there are two different keys. How can I sort this out?
by the first iteration of countriesIterator you have your domainIterator reached the end. You probably should include your Iterator<String> domainIterator = selectedDomains.iterator(); into countriesIterator loop so it started to iterate again from the beginning on the each iteration of countriesIterator.

WeightedLatLng and Collection<WeightedLatLng>

I am using the android API for heatmap. I've imported the dependencies and added the heatmap code at the end of my activity.
List<String> temp = Arrays.asList(coordinates.get(i).split(";"));
LatLng coor = new LatLng(Double.parseDouble(temp.get(1)), Double.parseDouble(temp.get(2)));
// Create a heat map tile provider, passing it the latlngs
WeightedLatLng data = new WeightedLatLng(coor, Double.parseDouble(temp.get(0)) );
mProvider = new HeatmapTileProvider.Builder()
//.weightedData(data) //doesn't work
.data(coor) //doesn't work either
.build();
}
I get the following error in the weightedData line:
WeightedData(java.util.Collection<com.google.maps.android.heatmaps.WeightedLatLng>) in Builder cannot be applies (com.google.maps.android.heatmaps.WeightedLatLng)
I tried adding a cast, but that makes the app crash. I have been googling for a long time and trying all kinds of things. Any ideas?
Builder weightedData and data methods take as a parameter a collection:
weightedData(Collection<WeightedLatLng> val)
Try adding all your data to an ArrayList and then pass it to your builder.
WeightedLatLng data = new WeightedLatLng(coor, Double.parseDouble(temp.get(0)) );
ArrayList<WeightedLatLng> weightedLatLngs = new ArrayList<>();
weightedLatLngs.add(data);
mProvider = new HeatmapTileProvider.Builder().weightedData(weightedLatLngs).build();
Ideally your heatmap should contain many weighted latlngs, so loop through your coordinates and add them all into the arraylist.
Hi i think you should write code like this
List<String> temp = Arrays.asList(coordinates.get(i).split(";"));
LatLng coor = new LatLng(Double.parseDouble(temp.get(1)), Double.parseDouble(temp.get(2)));
// Create a heat map tile provider, passing it the latlngs
WeightedLatLng data = new WeightedLatLng(coor, Double.parseDouble(temp.get(0)) );
mProvider = new HeatmapTileProvider.Builder();
mProvider.weightedData(data);
mProvider.data(coor);
mProvider = mProvider.build();

Break out multiple coordinates into multiple latlng googlemap v2

I have a huge list in an XML tag like so:
<coor> -123.3858,41.34119,0
-123.3856,41.34109,0
-123.3852,41.34121,0
-123.3848,41.34139,0</coor>
and need it like this:
new LatLng(-123.3858,41.34119),
new LatLng(-123.3856,41.34109),
new LatLng(-123.3852,41.34121),
new LatLng(-123.3848,41.34139),
to work with google maps v2 android.
I've done a string replace on the coordinates and am getting the correct results like so:
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
replacing the ,0 for the new LatLng(... I am not figuring out how to change the large string of latlng text into latlng locations to put into my polygon:
PolygonOptions perimeteres = new PolygonOptions().add(coor);
Is there way to do this? Or do I need to separate each out and make them individual latlng?
EDIT::::
String[] splitData = coor.split(",0");
for (String eachSplit : splitData) {
if (!eachSplit.endsWith(",0")) {
//Log.e("EACH",eachSplit);
Log.v("e","new LatLon("+eachSplit+");");
}
}
This is getting me a little closer...
You are going completely in the wrong direction, this
String ll = "),new LatLng(";
coor = coor.replaceAll(",0", ll);
is not the same as
new LatLng(-123.3858,41.34119)
the first gives you a string which does nothing for you, the second is an object which is what you need.
Edit
you need to remove the 0 from the coordinates then you do a string split on the , so you have an array of latitudes and longitudes.
then create a List<LatLng> which is what you need to create a polygon of points
and loop through your points
for(int j=0;j<locationAry.length;j++){
if(j%2 == 0){
lon = Float.parseFloat(locationAry[j+1]);
lat = Float.parseFloat(locationAry[j]);
}
}

value of integer in for loop do not changed android

I'm developing an Android app which is using Google Places API.
Once I get all the places result, I want to sort it according to the algorithm.
Which is, the places result will only being put into the Hash Map if the algorithm is >= 0.
But the problem now is, when I run it, the algorithm result in the for loop did not change during the looping.
My algorithm is:
balance = user_hour-visi-duration.
balance = 240-60-20 = 160
Let's say the balance is 160, it will remain 160 until the for loop ended.
I wanted each time of the looping, the value of balance will decreased untill negative value.
FYI, balance variable is not a local variable.
Does anybody know how to solve this?
Here is the part of the code.
// loop through each place
for (Place p : nearPlaces.results) {
balance = user_hour - duration - visit;
HashMap<String, String> map = new HashMap<String, String>();
//////////////////////////////////////////////////////////////////
googlePlaces = new GooglePlaces();
try {
placeDetails = googlePlaces.getPlaceDetails(p.reference);
} catch (Exception e) {
e.printStackTrace();
}
if(placeDetails != null){
String statuss = placeDetails.status;
// check place deatils status
// Check for all possible status
if(statuss.equals("OK")){
lat = gps.getLatitude();
lang = gps.getLongitude();
double endlat = placeDetails.result.geometry.location.lat;
double endlong = placeDetails.result.geometry.location.lng;
Location locationA = new Location("point A");
locationA.setLatitude(lat);
locationA.setLongitude(lang);
Location locationB = new Location("point B");
locationB.setLatitude(endlat);
locationB.setLongitude(endlong);
double distance = locationA.distanceTo(locationB)/1000;
Double dist = distance;
Integer dist2 = dist.intValue();
//p.distance = String.valueOf(dist2);
p.distance = String.valueOf(balance);
dist3 = p.distance;
}
else if(status.equals("ZERO_RESULTS")){
alert.showAlertDialog(MainActivity.this, "Near Places",
"Sorry no place found.",
false);
}
}
///////////////////////////////////////////////////////////////
if (balance > 0){
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
map.put(KEY_DISTANCE, p.distance);
// adding HashMap to ArrayList
placesListItems.add(map);
}
else {
//
}
}//end for loop
What exactly are you trying to do here?
You have balance = user_hour - duration - visit; on the first line after your for loop. I cannot see where user_hour, duration or visit is declared, but I'm assuming it's outside the loop. This means it will always be the same value for each Place in nearPlaces.results. If this code is genuinely how you want it, you might as well declare it before the loop as you are pointlessly re-calculating it for every Place.
You also never do anything with balance except to print it out or set another value to it, so it's tricky to work out what you're expecting to happen.

Populate listview according to distance

I am using gooleplaces API. I have a response in json, but the problem is I want to populate listview according to distance. I make the sorted distance arraylist in ascending order using collections.sort(), but how do I sort other lists based on this sorted list to populate my listview correctly?
If you are creating separate lists, then you need to your define method, and if you are using list of single collection, or data structure, you can define your comparator, then call sort on this, list.
Finally I resolve my problem using bubble sort.
if (distanceList.size()>1) // check if the number of orders is larger than 1
{
for (int i=0; i<distanceList.size()-1; i++) // bubble sort outer loop
{
for (int j=0; j < distanceList.size()-1-i; j++) {
if (distanceList.get(j)>(distanceList.get(j+1)) )
{
int temp = distanceList.get(j);
distanceList.set(j,distanceList.get(j+1) );
distanceList.set(j+1, temp);
String temp1 = nameList.get(j);
nameList.set(j,nameList.get(j+1) );
nameList.set(j+1, temp1);
String temp2 = vicinityList.get(j);
vicinityList.set(j,vicinityList.get(j+1) );
vicinityList.set(j+1, temp2);
String temp3 = latList.get(j);
latList.set(j,latList.get(j+1) );
latList.set(j+1, temp3);
String temp4 = longList.get(j);
longList.set(j,longList.get(j+1) );
longList.set(j+1, temp4);
}
}
}
}

Categories

Resources