Click here to Skip to main content
15,887,856 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
please How do i create an android application that checks and compare a list of latitude and longitude to the user's current location and displays places whose latitude and longitude are closest to the user's current location in a clickable listview. i have been able to access my location on the map and map out and also to map out a route from my location to a given coordinate but i don't know how to include a list of coordinates and compare them to my location so as to get it to display only the locations that are nearby. below is my java file and xml file. thank you

MYGIRNE.java
Java
package com.firsttry.cyptour;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.json.JSONObject;
 
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
 

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MYGIRNE extends FragmentActivity {
 
    GoogleMap map;
    ArrayList<latlng> markerPoints;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mygirne);
 
        // Initializing
        markerPoints = new ArrayList<latlng>();
 
        // Getting reference to SupportMapFragment of the activity_main
        SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
 
        // Getting Map for the SupportMapFragment
        map = fm.getMap();
 
        if(map!=null){
 
            // Enable MyLocation Button in the Map
            map.setMyLocationEnabled(true);
         // change map type to hybrid
            map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            // set traffic
            map.setTrafficEnabled(true);
            // get user location
            // Setting onclick event listener for the map
            LocationManager manager=(LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria criteria=new Criteria();
            String provider =manager.getBestProvider(criteria, true);
            Location cloc=manager.getLastKnownLocation(provider);
            double lat=35.177;
            double lng =33.3456;
             lat =cloc.getLatitude();
             lng= cloc.getLongitude();
			LatLng latlng = new LatLng (lat,lng);
            map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
           map.animateCamera(CameraUpdateFactory.zoomTo(15));
           map.addMarker(new MarkerOptions()
            .title("Your Current Location")
            .position(latlng));
            LatLng GIRNE = 
                    new LatLng(35.323710400000000000,33.314941299999990000);
            map.addMarker(new MarkerOptions()
            .position(GIRNE)
            .title("GIRNE")
            .snippet("GIRNE CITY CENTRE")
            .icon(BitmapDescriptorFactory.defaultMarker(
                      BitmapDescriptorFactory.HUE_AZURE)));
           
 
                        // Getting URL to the Google Directions API
                        String url = getDirectionsUrl(latlng, GIRNE);
 
                        DownloadTask downloadTask = new DownloadTask();
 
                        // Start downloading json data from Google Directions API
                        downloadTask.execute(url);
                    }
                }
         
        
    
 
    private String getDirectionsUrl(LatLng latlng,LatLng GIRNE){
 
        // Origin of route
        String str_origin = "origin="+latlng.latitude+","+latlng.longitude;
 
        // Destination of route
        String str_dest = "destination="+GIRNE.latitude+","+GIRNE.longitude;
 
        // Sensor enabled
        String sensor = "sensor=true";
 
        // Building the parameters to the web service
        String parameters = str_origin+"&"+str_dest+"&"+sensor;
 
        // Output format
        String output = "json";
 
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
 
        return url;
    }
    /** A method to download json data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
            URL url = new URL(strUrl);
 
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
 
            // Connecting to url
            urlConnection.connect();
 
            // Reading data from url
            iStream = urlConnection.getInputStream();
 
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
 
            StringBuffer sb = new StringBuffer();
 
            String line = "";
            while( ( line = br.readLine()) != null){
                sb.append(line);
            }
 
            data = sb.toString();
 
            br.close();
 
        }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
        }finally{
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
 
    // Fetches data from url passed
    private class DownloadTask extends AsyncTask<string,>{
 
        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
 
            // For storing data from web service
            String data = "";
 
            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }
 
        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
 
            ParserTask parserTask = new ParserTask();
 
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }
 
    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<string,>>> >{
 
        // Parsing the data in non-ui thread
        @Override
        protected List<list><hashmap><string,>>> doInBackground(String... jsonData) {
 
            JSONObject jObject;
            List<list><hashmap><string,>>> routes = null;
 
            try{
                jObject = new JSONObject(jsonData[0]);
                Directions parser = new Directions();
 
                // Starts parsing data
                routes = parser.parse(jObject);
            }catch(Exception e){
                e.printStackTrace();
            }
            return routes;
        }
 
        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(List<list><hashmap><string,>>> result) {
            ArrayList<latlng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();
 
            // Traversing through all the routes
            for(int i=0;i<result.size();i++){>
                points = new ArrayList<latlng>();
                lineOptions = new PolylineOptions();
 
                // Fetching i-th route
                List<hashmap><string,>> path = result.get(i);
 
                // Fetching all the points in i-th route
                for(int j=0;j<path.size();j++){>
                    HashMap<string,string> point = path.get(j);
 
                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);
 
                    points.add(position);
                }
 
                // Adding all the points in the route to LineOptions
                lineOptions.addAll(points);
                lineOptions.width(5);
                lineOptions.color(Color.CYAN);
            }
 
            // Drawing polyline in the Google Map for the i-th route
            map.addPolyline(lineOptions);
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mygirne, menu);
        return true;
    }
}
mygirne.xml

XML
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android">
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.firsttry.cyptour.MYGIRNE" >

    <fragment>
        android:id="@+id/map"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="com.google.android.gms.maps.SupportMapFragment" />

</fragment></relativelayout>
AndroidManifest.xml


XML
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    package="com.firsttry.cyptour"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk>
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!-- External storage for caching. -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- My Location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- Maps API needs OpenGL ES 2.0. -->
    <uses-feature>
        android:glEsVersion="0x00020000"
        android:required="true" />

    <permission>
        android:name="com.firsttry.cyptour.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" >
    </permission>

    <application>
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDgRSTCYVtoc3vLqRR-XX0_RkyoofblyXc" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

       
        <activity>
            android:name=".MYGIRNE"
            android:label="@string/title_activity_mygirne" >
        </activity>
        
    </application>
Posted
Updated 17-Nov-14 13:23pm
v4

This is not how CP usually works. Most important goal here is to learn and help learning.
You are supposed to try it on your own, and come here when you got stuck with something, with a concrete question about your code, design, etc.
Please have a look to What have you tried?[^] to see a good explanation about what I mean.
Don't forget people here don't get payed. And besides, if we give you a ready-to-go solution, it is not going to help you because you are not going to learn anything from it.

As a general approach:
Step 1) Do a little research. Google is a good start point
ie. Places to start:
http://developer.android.com/index.html[^]
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html[^]
http://www.youtube.com/watch?v=7-n6p6RxSS8[^]

Step 2) Start coding
Step 3) Compile and use the debug to solve little issues
Step 4) When you get a problem you don't know how to solve but at least you tried it, then come back and ask for something concrete with a snippet of the code giving problems

Sorry if this is not the answer you were looking for. But your question is a bit too wide to be answered at the "Quick" Answers. It is better and you get faster help if you make 10 concrete questions about concrete problems, than a big question about a "how-to guide"
 
Share this answer
 
Comments
Kathy Kefas 17-Nov-14 18:46pm    
thank you.
I have actually started something but got stocked not like i haven't tried, i just didn't know i was suppose to post it.
I was able to access my location on the map and also to map out a route from my location to a given coordinate but i don't know how to include a list of coordinates and compare them to my location so as to get it to display only the locations that are nearby. below is my java file and xml file

MYGIRNE.java

package com.firsttry.cyptour;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;


import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MYGIRNE extends FragmentActivity {

GoogleMap map;
ArrayList<latlng> markerPoints;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygirne);

// Initializing
markerPoints = new ArrayList<latlng>();

// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

// Getting Map for the SupportMapFragment
map = fm.getMap();

if(map!=null){

// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// change map type to hybrid
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// set traffic
map.setTrafficEnabled(true);
// get user location
// Setting onclick event listener for the map
LocationManager manager=(LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
String provider =manager.getBestProvider(criteria, true);
Location cloc=manager.getLastKnownLocation(provider);
double lat=35.177;
double lng =33.3456;
lat =cloc.getLatitude();
lng= cloc.getLongitude();
LatLng latlng = new LatLng (lat,lng);
map.moveCamera(CameraUpdateFactory.newLatLng(latlng));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
map.addMarker(new MarkerOptions()
.title("Your Current Location")
.position(latlng));
LatLng GIRNE =
new LatLng(35.323710400000000000,33.314941299999990000);
map.addMarker(new MarkerOptions()
.position(GIRNE)
.title("GIRNE")
.snippet("GIRNE CITY CENTRE")
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_AZURE)));


// Getting URL to the Google Directions API
String url = getDirectionsUrl(latlng, GIRNE);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}




private String getD
Start research into Creating and Monitoring Geofences[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900