I want to get distance by road by foot and by car in my app.I have already got distance by line but now I want the exact distance. I have read to enable billing for google account for API key and I have done that. Now I couldn't understand he code I have seen multiple and tried them but can't understand how to use the API available at google guide. Sometimes the app crashes and sometime it gives nothing in response.
On priority what I want to do is to get the exact distance only it can be on foot or on vehicle any. Any help will be very grateful
The last code which I tried but its doing nothing
origin = new LatLng(currentLat, currentLong);
dest = new LatLng(donarLat, donarLong);
String url = getDirectionsUrl();
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
private String getDirectionsUrl() {
// Origin of route
String str_origin = "origin=" + currentLat + "," + currentLong;
// Destination of route
String str_dest = "destination=" + donarLat + "," + donarLong;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String key = "key=" + "**********NR9TxLUwXyeq0jwV6k************";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + key;
// 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) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
}
return returnList;
} catch (Exception e) {
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
ParserTask parserTask = new ParserTask();
for (String url : results) {
parserTask.execute(url);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
// for (String url : jsonData) {
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
}
return routes;
} catch (Exception e) {
Log.d("Background task", e.toString());
return null; // Failed, return null
}
}
#Override
protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) {
Toast.makeText(DonarList.this, "No Points", Toast.LENGTH_LONG).show();
return;
}
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
Log.d("Distance: ", distance);
Toast.makeText(DonarList.this, "Your Distance ya hy :" + distance, Toast.LENGTH_SHORT).show();
}
Related
i have android map with multiple points plotted from mysql data..i have added basic features of map like mylocation,zoom etc...Also added direction between multiple points from mylocation.
Now I need to add step by step direction route or navigate between points.
Most importantly i dont want to redirect to google maps and naviagate..
all actions should happen withen my google map api.
here is my Mapactivity code onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Toast.makeText(getActivity(), Util.reslatitude + " " + Util.reslogitide+" "+Util.resname, Toast.LENGTH_LONG).show();
LatLng locations = new LatLng(Util.latitude,Util.longitude);
/* Location startPoint=new Location("locationA");
startPoint.setLatitude(Util.latitude);
startPoint.setLongitude(Util.longitude);
Location endPoint=new Location("locationA");
endPoint.setLatitude(13.073226);
endPoint.setLongitude(80.260921);
double distance=startPoint.distanceTo(endPoint);
Toast.makeText(this,String.valueOf(distance+" Meters"),Toast.LENGTH_SHORT).show();*/
/* LatLng loc = new LatLng(13.073226, 80.260921);*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
//mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
mMap.getUiSettings().setMapToolbarEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setTrafficEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 4.2f));
mMap.addMarker(new MarkerOptions()
.title("User")
.position(locations)
);
/* // Getting URL to the Google Directions API
String url = getDirectionsUrl(locations, loc);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);*/
/*LatLng dest = new LatLng(13.036791,80.26763);
mMap.addPolyline(new PolylineOptions().add(locations,dest).color(Color.RED) //draws straight line between points
);*/
}
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < result.size(); i++) {
points = new ArrayList();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
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);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.BLUE);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// 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);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
help me to rectify the problem
I want to find the shortest location to the current location of the user.
i use distanceTo() and distanceBetween() but it's not working
The process of my android app is the location of the places is automatically initialized in the variable and i want to compare it to the multiple location and find the shortest location and print the location .
can anyone help me about my problem ? thanks in advance
Try this,
public class Nav extends Fragment {
GoogleMap map;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Commons.applyFont(getActivity(), getView().findViewById(R.id.frame),
"RobotoSlab-Light");
map = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
LatLng latLng = new LatLng(nav.sAddLat, nav.sAddLong);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.0f));
map.addMarker(new MarkerOptions().position(new LatLng(nav.sAddLat,
nav.sAddLong)));
map.getUiSettings().setCompassEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).tilt(60).zoom(15.0f).bearing(300).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng origin = new LatLng(nav.sAddLat, nav.sAddLong);
LatLng dest = new LatLng(nav.dAddLat, nav.dAddLong);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + ","
+ origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + parameters;
return url;
}
#SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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;
}
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJsonParser parser = new DirectionsJsonParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
Log.e("results", result + "");
if (result.size() < 1) {
Toast.makeText(getActivity(), "No Points", Toast.LENGTH_SHORT)
.show();
return;
}
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
List<HashMap<String, String>> path = result.get(i);
Log.e("points", path + "");
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
tvDistance.setText("Distance : "
+ point.get("distance"));
} else if (j == 1) {
tvTime.setText("Duration : " + point.get("duration"));
} else if (j > 1) {
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
}
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
map.addPolyline(lineOptions);
}
}
}
I have a problem concerning execution order.I get some data from server ( cities names , LatLng) and on onPostExecute i'm trying to calculate distances between cities. During last onPostExecute there are some distance calculations. The problem is that in
for(j=0;j<3;j++) {
or = markerPoints.get(j);
dest = markerPoints.get(j+1);
Log.d("or", or.toString());
Log.d("dest", dest.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(or, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
downloadTask is executed for the first time after loop "for" is completed, that means when j equals 2. Why not 3 times; Isn't that weird;
My whole code
public class Check_Itineraries1 extends FragmentActivity {
private ProgressDialog pDialog;
String username , origin_lat ,origin_lng ,destination_lat ,destination_lng ,
waypoint1_lat ,waypoint1_lng ,waypoint2_lat ,waypoint2_lng ,waypoints ,
origin_lat_pro ,origin_lng_pro ,destination_lat_pro ,destination_lng_pro , start_pro , final_pro;
int i, j ,b ;
double x,z ,t ,s;
TextView v1 , v2;
ArrayList<Double> Array = new ArrayList<Double>();
ArrayList<Double> Array_add = new ArrayList<Double>();
ArrayList<Double> Array_dif = new ArrayList<Double>();
ListView list;
ArrayList<LatLng> markerPoints;
// URL to get contacts JSON
private static String LOGIN_URL = "http://**************************";
public static final String PREFS_NAME = "MyPreferencesFile";
// JSON Node names
JSONParser jsonParser = new JSONParser();
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> itinList , final_itinList ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkitineraries);
itinList = new ArrayList<HashMap<String, String>>();
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, Void> {
public void onPreExecute() {
super.onPreExecute();
Log.d("meg", "meg");
pDialog = new ProgressDialog(Check_Itineraries1.this);
pDialog.setMessage("Επεξεργάζομαι τα δεδομένα...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
username = settings.getString("username", "nikos");
}
protected Void doInBackground(Void... args) {
// TODO Auto-generated method stub
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// JSONObject jObj = new JSONObject();
JSONArray itin_results = json.getJSONArray("itin_results");
for (int i = 0; i < itin_results.length(); i++) {
JSONObject c = itin_results.getJSONObject(i);
String username = c.getString("username");
String startPoliPro = c.getString("startPoliPro");
String start_lat_pro = c.getString("start_lat_pro");
String start_lng_pro = c.getString("start_lng_pro");
String finalPoliPro = c.getString("finalPoliPro");
String final_lat_pro = c.getString("final_lat_pro");
String final_lng_pro = c.getString("final_lng_pro");
LinkedHashMap<String, String> pinakas = new LinkedHashMap<String, String>();
// adding each child node to HashMap key => value
pinakas.put("username", username);
pinakas.put("startPoliPro", startPoliPro);
pinakas.put("start_lat_pro", start_lat_pro);
pinakas.put("start_lng_pro", start_lng_pro);
pinakas.put("finalPoliPro", finalPoliPro);
pinakas.put("final_lat_pro", final_lat_pro);
pinakas.put("final_lng_pro", final_lng_pro);
// Διαλέγω αφετηρία και προορισμό του δρομολογίου του επαγγελματία
Log.d("1", username);
Log.d("2", startPoliPro);
Log.d("3", start_lat_pro);
Log.d("4", start_lng_pro);
Log.d("5", finalPoliPro);
Log.d("6", final_lat_pro);
Log.d("7", final_lng_pro);
itinList.add(pinakas);
b = itin_results.length(); // Είναι τα δρομολόγια των πελατων που ταιριάζουν ΣΥΝ το δρομολόγιο του επαγγελματία
Log.d("b", String.valueOf(b));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
origin_lat_pro = itinList.get(0).get("start_lat_pro").toString();
origin_lng_pro = itinList.get(0).get("start_lng_pro").toString();
destination_lat_pro = itinList.get(0).get("final_lat_pro").toString();
destination_lng_pro = itinList.get(0).get("final_lng_pro").toString();
start_pro = itinList.get(0).get("startPoliPro").toString();
final_pro = itinList.get(0).get("finalPoliPro").toString();
LatLng origin_pro = new LatLng(Double.parseDouble(origin_lat_pro),Double.parseDouble(origin_lng_pro));
LatLng destination_pro = new LatLng(Double.parseDouble(destination_lat_pro),Double.parseDouble(destination_lng_pro));
for (i = 0; i <b; i++) {
markerPoints = new ArrayList<LatLng>();
origin_lat = itinList.get(i).get("start_lat_pro").toString();
origin_lng = itinList.get(i).get("start_lng_pro").toString();
destination_lat = itinList.get(i).get("final_lat_pro").toString();
destination_lng = itinList.get(i).get("final_lng_pro").toString();
LatLng or = new LatLng(Double.parseDouble(origin_lat),Double.parseDouble(origin_lng));
LatLng dest = new LatLng(Double.parseDouble(destination_lat),Double.parseDouble(destination_lng));
markerPoints.add(origin_pro);
markerPoints.add(or);
markerPoints.add(dest);
markerPoints.add(destination_pro);
Log.d("a", markerPoints.get(0).toString());
Log.d("b", markerPoints.get(1).toString());
Log.d("c", markerPoints.get(2).toString());
Log.d("d", markerPoints.get(3).toString());
z = 0;
for(j=0;j<3;j++) {
or = markerPoints.get(j);
dest = markerPoints.get(j+1);
Log.d("or", or.toString());
Log.d("dest", dest.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(or, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
}
//Αυτοτελές
private String getDirectionsUrl(LatLng or, LatLng dest) {
// Origin of route
String str_origin = "origin=" + or.latitude + ","+ or.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
Log.d("sos1", "sos1");
// 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;
}
//Αυτοτελές//
//Αυτοτελές
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();
Log.d("sos2", "sos2");
// 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, Void, 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]);
Log.d("sos3", "sos3");
} 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();
Log.d("sos4", "sos4");
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
//Αυτοτελές//
public class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
Log.d("sos5", "sos5");
// Starts parsing data
routes = parser.parse(jObject);
Log.d("json", jObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
String distance = "";
String duration = "";
Log.d("sos6", "sos6");
Log.d("result", String.valueOf(result.size()));
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
// Fetching i-th route
List<HashMap<String, 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);
if(j==0){ // Get distance from the list
distance = point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
//
//
}
}
Log.d("finito", distance);
String asd[] = distance.split(" ");
Log.d("ass", asd[0]);
Log.d("ass", asd[1]);
double x = Double.parseDouble(asd[0]);
if(asd[1].equals("m")){
x = x/1000;
}
Log.d("intValue", String.valueOf(x));
x = Math.round(x);
Array.add(x);
Log.d("Array", Array.toString());
if(Array.size()==3){
z = Array.get(0) + Array.get(1) + Array.get(2);
Array_add.add(z);
Array.clear();
}
Log.d("size", String.valueOf(Array_add.size()));
Log.d("Αθροισμα", String.valueOf(z));
}
}
//Αυτοτελές
}
Android Developers says:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with
{android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool
of threads allowing multiple tasks to operate in parallel. Starting
with { android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed
on a single thread to avoid common application errors caused by
parallel execution.
Also since executor of AsyncTask is static so you get single executor of your application.
Now it already running GetData asyncTask and it runs asynsTask serially so it cannot execute your DownloadTask. It can run only after GetDataTask is finished.
If you want to run multiple asynctasks in parallel, you can look at Asynctask.executeOnExecutor().
I want to draw route between my current location(Like Indore ) to Saudi Arabia.
I am able to draw route between indore to delhi ..but not from indore to saudi arabia.
I tried using intent by passing my lat long and saudi arabia's lat long, but google map app shows no route.
How can i do this?
You should make a call to the google directions api and draw a polyline on the map manually. You can use this methods:
public void setRoute() {
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Mode travel
//String mode = "mode=" + modeT; Uncomment this if you want choose a travel mode (driving, walking or transit)
// Departure Time, its neccesary to public transport
String departureTime = "";
if (modeT.equals("transit")) {
long seconds = (System.currentTimeMillis() / 1000);
departureTime = "&departure_time=" + seconds;
}
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode + departureTime;
// 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, Void, 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 = ActFullMapOne.this.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, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData)
{
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try
{
jObject = new JSONObject(jsonData[0]);
ApiDirectionsParser parser = new ApiDirectionsParser();
// 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, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
//MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if (result.size() < 1) {
Toast.makeText(ActFullMapOne.this.getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// 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, 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);
if (j == 0) {
distance = point.get("distance");
continue;
} else if (j == 1) {
duration = point.get("duration");
continue;
}
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(7);
lineOptions.color(Color.parseColor("#CC0060FF"));
}
// Drawing polyline in the Google Map for the i-th route
if (polyline != null)
polyline.remove();
polyline = ActFullMapOne.this.nMap.addPolyline(lineOptions);
}
}
EDIT 1. I just read your post better and I've seen that you only want to open the route on google maps. If you want to display the route on google maps app, use this method:
public void goToNavigation() {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" + modLugar.latitud + "," + modLugar.longitud));
startActivity(Intent.createChooser(i, "Elige una aplicación"));
}
Hi i am first time using the map in android after changing in google Map API.
Now I wants to draw the route on the map between two addresses endered by me for API v2. I don't know how to do this.
I tried a lot for this.
Please help me. Thanks.
My code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.start_trip_view);
try {
ArrayList<String> location = new ArrayList<String>();
Intent ii = getIntent();
location2 = (ii.getStringExtra("place"));
String location3 = (ii.getStringExtra("start"));
gps = new GPSTracker(getApplicationContext());
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Balvinder = new LatLng(latitude, longitude);
markerPoints = new ArrayList<LatLng>();
map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
//
if (location == null || location.equals("")) {
Toast.makeText(getBaseContext(), "No Place is entered",
Toast.LENGTH_SHORT).show();
return;
}
String url = "https://maps.googleapis.com/maps/api/geocode/json?";
// for(int i=0; i<location.size();i++)
// {
try {
// encoding special characters like space in the user input
// place
location2 = URLEncoder.encode(location2, "utf-8");
// location3 = URLEncoder.encode(location3, "utf-8");
String saddress = "address=" + location2;
// String Dsaddress = "address=" + location3;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + saddress + "&" + sensor;
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
private String downloadUrl(String... strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
for(int i=0;i<strUrl.length;i++)
{
URL url = new URL(strUrl[i]);
// 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, Integer, String> {
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
for(int i=0;i<url.length;i++)
{
data = downloadUrl(url[i]);
}
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
// Instantiating ParserTask which parses the json data from
// Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
System.out.println("Result"+result);
}
}
/** A class to parse the Google Places in JSON format */
class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
PolylineOptions lineOptions = new PolylineOptions();
ArrayList<LatLng>points=new ArrayList<LatLng>();
// Clears all the existing markers
map.clear();
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("formatted_address");
latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// getDirectionsUrl(Balvinder, latLng);
// markerOptions.position(Balvinder);
.show();
map.addMarker(new MarkerOptions().title("My Location").snippet(
gps.ConvertPointToLocation(latitude, longitude,
StartTripView.this))
.position(Balvinder)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.logo_sono)));
markerPoints.add(Balvinder);
markerPoints.add(latLng);
//makeURL(latitude, longitude, lat, lng);
System.out.println("Result"+makeURL(latitude, longitude, lat, lng));
// Polyline line = map.addPolyline(new PolylineOptions()
// .add(Balvinder, latLng)
// .width(5)
// .color(Color.RED).geodesic(true));
markerOptions.title(name);
//
map.addMarker(markerOptions);
if (i == 0){
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
}
Documentation: https://developers.google.com/maps/documentation/android/shapes?hl=fr#polylines
To draw the route between 2 locations, you should use a polyline:
// Instantiates a new Polyline object and adds points to define a rectangle
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
In your case you won't need the last point to close the polyline.
Check this example Driving Direction
You can use Reverse Geocoding
Geocoder geocoder = new Geocoder(context);
address = geocoder.getFromLocationName("your address");
get lat/lng from the address and pass that in the above example.
Please first check ur api response is your key is valid the use my below asynctask code
private class DownloadTask extends AsyncTask {
ProgressDialog asyncDialog = new ProgressDialog(NearGoogleMap.this);
String StatusOK="", url;
String data = "";
JSONArray routeArray=null,LegsArray=null,StepsArray=null;
public DownloadTask(String url) {
this.url=url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
asyncDialog.setMessage("Please wait...!!!");
//show dialog
asyncDialog.setCancelable(false);
asyncDialog.show();
}
#Override
protected Object doInBackground(Object[] params) {
try {
data = downloadUrl(url);
Log.d("Background data Task", data.toString());
if (data.isEmpty())
{
}else {
JSONObject dataJSON =new JSONObject(data);
Log.d("data JSON", dataJSON.toString());
StatusOK=dataJSON.getString("status");
if (StatusOK.equals("OK"))
{
Log.d("Decode JSON","StatusOK");
routeArray=dataJSON.getJSONArray("routes");
for (int i=0;i<routeArray.length();i++)
{
Log.d("Decode JSON","routes");
JSONObject inputJSON=routeArray.getJSONObject(i);
LegsArray=inputJSON.getJSONArray("legs");
for (int j=0;j<LegsArray.length();j++)
{
Log.d("Decode JSON","legs");
JSONObject inputJSONleg=LegsArray.getJSONObject(j);
StepsArray=inputJSONleg.getJSONArray("steps");
for (int k=0;k<StepsArray.length();k++)
{
Log.d("Decode JSON","steps");
JSONObject inputJSONstep=StepsArray.getJSONObject(k);
JSONObject PolylineJSON=inputJSONstep.getJSONObject("polyline");
Log.d("Decode JSON","polyline");
String getPolylineString=PolylineJSON.getString("points");
Log.d("Decode JSON","points");
List<LatLng> getPolypont=decodePolyNew(getPolylineString);
Log.d("Decode JSON","decodePolyNew");
for (int z=0;z<getPolypont.size();z++)
{
Log.d("Decode JSON","DirectionPoint");
DirectionPoint.add(new LatLng(getPolypont.get(z).latitude,getPolypont.get(z).longitude));
}
}
}
}
}
}
} catch (Exception e) {
Log.d("Background Task", e.toString());
data="";
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
asyncDialog.dismiss();
if (data.isEmpty())
{
Toast.makeText(getBaseContext(),"Something went wrong",Toast.LENGTH_SHORT).show();
}else {
if (DirectionPoint.size()==0)
{
}else {
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < DirectionPoint.size(); z++) {
LatLng point = DirectionPoint.get(z);
options.add(point);
}
mMap.addPolyline(options);
}
}
}
}
// Inside onCreate() method call asynctask as follows
if (points.size()>=2)
{
// Getting URL to the Google Directions API
String url = getDirectionsUrl(points.get(0), points.get(1));
Log.d("Get URL",url);
DownloadTask downloadTask = new DownloadTask(url);
// Start downloading json data from Google Directions API
downloadTask.execute();
}
}
// binding url getDirectionsUrl()
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String mode = "mode=driving";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
// 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;
}
// for decode polyline use this method
private List decodePolyNew(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}