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"));
}
Related
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();
}
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 am working with a project to find the distance between two places, one is current location and other is user input value using auto-complete text view.
How can I get the correct distance using button click. I got the values without a button click. How can I implement button click?
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MarkerPoints = new ArrayList<>();
final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
b1=(Button)findViewById(R.id.search_button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String location = autoCompView.getText().toString();
List<Address>addressList = null;
if (location != null || !location.equals("")) {
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng dest = new LatLng(address.getLatitude(), address.getLongitude());
lat1=String.valueOf(address.getLatitude());
lon1 = String.valueOf(address.getLongitude());
Toast.makeText(MapsActivity.this, "new Lati and new longi1 "+dest, Toast.LENGTH_LONG).show();
mMap.addMarker(new MarkerOptions().position(dest).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(dest));
// SendDataToServer(unique_id,lat1,lon1);
// mMap.clear();
findPath(point);
}
}
});
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
private void findPath(LatLng point) {
if (MarkerPoints.size() >= 2) {
LatLng origin = MarkerPoints.get(0);
LatLng dest = MarkerPoints.get(1);
// Getting URL to the Google Directions API
String url = getUrl(origin, dest);
// Log.d("onMapClick", url.toString());
FetchUrl FetchUrl = new FetchUrl();
// Start downloading json data from Google Directions API
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(origin));
mMap.animateCamera(CameraUpdateFactory.zoomTo(16));
}
}
private void drawMarker(LatLng point) {
MarkerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
private String getUrl(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";
// 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();
Log.d("downloadUrl", data.toString());
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class FetchUrl extends AsyncTask<String, Void, String> {
#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("Background Task data", data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#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]);
Log.d("ParserTask",jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask","Executing routes");
Log.d("ParserTask",routes.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
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;
PolylineOptions lineOptions = null;
String distance = "";
String duration = "";
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
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){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)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(10);
lineOptions.color(Color.RED);
Log.d("onPostExecute","onPostExecute lineoptions decoded");
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
}
// Drawing polyline in the Google Map for the i-th route
if(lineOptions != null) {
mMap.addPolyline(lineOptions);
}
else {
Log.d("onPostExecute","without Polylines drawn");
}
}
If you know the latitude and longitude of both locations then you can easily calculate the distance between both position. Visit http://www.geodatasource.com/developers/java for more information.
Here is how you can do it in android.
Create a method as following in some class
private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == "K") {
dist = dist * 1.609344;
} else if (unit == "N") {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private static double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
Then you can use distance method
For example distance is static method of Helper Class then
int distance = Helper.distance(lat1,lon1,lat2,lon2,"K") use "K" for kilometer "N" for
I hope this will help you somehow.
This is the method I use to get the distance and time travel from user location to selected location. Add it below your AsyncTask:
public void getDistAndDuration(JSONObject jObj){
try{
JSONArray array = jObj.getJSONArray("routes");
JSONObject rou = array.getJSONObject(0);
JSONArray legs = rou.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
JSONObject duration = steps.getJSONObject("duration");
final String textDist = distance.getString("text");
final String textDur = duration.getString("text");
Log.i("DISTANCE", ""+textDist);
Log.i("TIME", ""+textDur);
}catch(Exception e){
e.printStackTrace();
}
}
Call this method in your ParserTask in the doInBackground method like this:
#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]);
////////// HERE //////////////
getDistAndDuration(jObject);
//////////////////////////////
Log.d("ParserTask",jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("ParserTask", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("ParserTask","Executing routes");
Log.d("ParserTask",routes.toString());
} catch (Exception e) {
Log.d("ParserTask",e.toString());
e.printStackTrace();
}
return routes;
}
If you only want to get the distance on button click, declare your jObject globally, and call the getDistAndDuration(JSONObject jObj) in the click listener of your button. Be sure to call it after you called the AsyncTask first.
Hope it helps :)
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);
}
}
}
Friends,
Am able to fetch the latitude and longitude from SqliteDb to place a marker in google Map respectively.
But my problem is
1. I want to draw a route from current location to the latitude and longitude fetched from Sqlite Db
2. The db values of Latitude and Longitude will be changed every 2 minutes and i want to change the place in marker accordingly and also route between the updated values and current location.
I have tried running the below code.
It runs perfect in Main class but when I tried using thread it fails and since used timer for the same.
protected void mLocActivity() {
db.open();
class preciLoc extends TimerTask{
#Override
public void run() {
Cursor cr = db.fetchone(sLoc, "pos_mark", tblName, "pho", null, null);
if(cr.getCount()>0){
sLat = cr.getString(cr.getColumnIndex("lat"));
sLon = cr.getString(cr.getColumnIndex("lon"));
}
LatLng orgLoc = new LatLng(mLatitude,mLongitude);
LatLng desCur = new LatLng(Double.parseDouble(sLat), Double.parseDouble(sLon));
String url = getDirectionsUrl(orgLoc, desCur);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
rMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
CameraPosition camPos1 = new CameraPosition.Builder()
.target(destCurr).zoom(15).bearing(90).tilt(30).build();
rMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPos1));
drawMarker(desCur);
}
}
Timer timer = new Timer();
timer.schedule(new preciLoc(), 50000);
}
The solutions to your question are :-
The following code is used to display route from one point to another-
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
}
}
Include the above class and then add the following codes to the class where you want to display the route to the map-
/** 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 = 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]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// 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();
// 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);
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(4);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.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";
// 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;
}
Now the call starts as follows-
// Getting URL to the Google Directions API
String url = getDirectionsUrl(new LatLng(userLocation.getLatitude(),
userLocation.getLongitude()), new LatLng(
dest_lat, dest_long));
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Here user userLocation is my current location and dest_lat, dest_long is the destination lat, long and in onPostExecute of ParserTask the line "map.addPolyline(lineOptions);" adds route to the map, so replace it with your own map.
Now for this problem create a thread and put a sleep of 2 min or more. Inside that thread call the database and retrive the lat,long and call the above methods(solution 1) , thus your route gets refreshed on every 2 min or more and don't forget to call map.clear() to clear the existing route.
Here is my implementation of timerTask and its working fine -
public class Test extends Activity {
Timer timer;
preciLoc loc;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
..........
timer = new Timer();
loc = new preciLoc();
timer.schedule(loc,5000, 10000);
}
class preciLoc extends TimerTask {
#Override
public void run() {
Log.e("preciLoc", timer.toString());
}
}
}
Here I have set a constant delay of 10 sec and a initial delay of 5 sec, its working fine.