Android Google Map How to Parse alternate route's distance - android

I will be posting all of my codes here and a sample output of my project. I have set the alternative to yes to display the alternate routes but problem is, how do I parse all the distance from all routes? It only gets the distance of the main route but not the alternate routes. How do I change my Parse java class to get all the directions in alternate routes and display it?
public class ThirdFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener,DirectionFinderListener,AdapterView.OnItemClickListener {
/**************************************************************/
// private GoogleMap mMap;
private ImageButton btnFindPath;
private AutoCompleteTextView etOrigin;
private AutoCompleteTextView etDestination;
private List<Marker> originMarkers = new ArrayList<>();
private List<Marker> destinationMarkers = new ArrayList<>();
private List<Polyline> polylinePaths = new ArrayList<>();
private ProgressDialog progressDialog;
private static final String LOG_TAG = "Google Places Autocomplete";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "MY API KEY HERE";
//FOR COLLAPSING TOOLBAR
private CollapsingToolbarLayout collapsingToolbarLayout = null;
/**************************************************************************************************************/
double latitude;
double longitude;
GoogleMap mMap;
MapView mapView;
View Myview;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Myview = inflater.inflate(R.layout.activity_third_fragment, container, false);
mapView = (MapView) Myview.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
/********************************************************************/
collapsingToolbarLayout = (CollapsingToolbarLayout) Myview.findViewById(R.id.collapsing_toolbar);
/****************************************************************************************/
btnFindPath = (ImageButton) Myview.findViewById(R.id.btnFindPath);
etOrigin = (AutoCompleteTextView) Myview.findViewById(R.id.etOrigin);
etDestination = (AutoCompleteTextView) Myview.findViewById(R.id.etDestination);
btnFindPath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendRequest();
}
});
etOrigin.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
etOrigin.setOnItemClickListener(this);
etDestination.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
etDestination.setOnItemClickListener(this);
return Myview;
}
//**********For changing colors in the directions************************************************************/
/**************************************************************************************************************/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
goToLocationZoom(9.3068, 123.3054, 15);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
LatLngBounds Dumaguete = new LatLngBounds(new LatLng(9.267, 123.264), new LatLng(9.33, 123.311));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMinZoomPreference(15.0f);
mMap.setMaxZoomPreference(20.0f);
mMap.setLatLngBoundsForCameraTarget(Dumaguete);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Dumaguete.getCenter(), 15));
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
private void goToLocationZoom(double lat, double lng, int zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
private void sendRequest() {
String origin = etOrigin.getText().toString();
String destination = etDestination.getText().toString();
if (origin.isEmpty()) {
Toast.makeText(getActivity(), "Please enter origin address!", Toast.LENGTH_SHORT).show();
return;
}
if (destination.isEmpty()) {
Toast.makeText(getActivity(), "Please enter destination address!", Toast.LENGTH_SHORT).show();
return;
}
try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(getActivity(), "Please wait.",
"Finding direction..!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline : polylinePaths) {
polyline.remove();
}
}
}
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show();
for (final Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text); //For Distance
originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue))
.title(route.startAddress)
.position(route.startLocation)));
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green))
.title(route.endAddress)
.position(route.endLocation)));
/******************For Changing color ********************************************************/
mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
// Flip the values of the red, green and blue components of the polyline's color.
polyline.setColor(polyline.getColor() ^ 0x00ffffff);
// Toast.makeText(getActivity(), "Hello", Toast.LENGTH_SHORT).show();
}
});
/*************************************************************************************************/
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258));
/**/
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).color(color).width(15).clickable(true);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&types=establishment&strictbounds&location=9.30684,123.305447&radius=2000");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return String.valueOf(resultList.get(index));
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
// mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}//End of CLass ThirdFragment.java
This is my Data Parsing and how do I change it to also get the distance of the alternate routes?
DirectionFInder.java
import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class DirectionFinder {
private static final String DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?";
private static final String GOOGLE_API_KEY = "AIzaSyC1E8NU2jjoQF7dN37bIOz_1fy0fe98YhI";
private DirectionFinderListener listener;
private String origin;
private String destination;
public DirectionFinder(DirectionFinderListener listener, String origin, String destination) {
this.listener = listener;
this.origin = origin;
this.destination = destination;
}
public void execute() throws UnsupportedEncodingException {
listener.onDirectionFinderStart();
new DownloadRawData().execute(createUrl());
}
private String createUrl() throws UnsupportedEncodingException {
String urlOrigin = URLEncoder.encode(origin, "utf-8");
String urlDestination = URLEncoder.encode(destination, "utf-8");
return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination +"&alternatives=true" +"&key=" + GOOGLE_API_KEY;
}
private class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String link = params[0];
try {
URL url = new URL(link);
InputStream is = url.openConnection().getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String res) {
try {
parseJSon(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}
private List<LatLng> decodePolyLine(final String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new ArrayList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng(
lat / 100000d, lng / 100000d
));
}
return decoded;
}
}
This is the screenshot of the application.
The dark green color is the main route and the pink and blue are the alternate routes. How can I get the distance of the pink and blue as well? Please help.

You are already looping through all of the routes, so storing the distance for each route should be simple. This line of code is where you get the distance for each route:
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));'
If you create an array, you can store the value of each route during each iteration of the loop. Let's say you have an array called routeDistances[]. You could do something like this:
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
routeDistances[i] = jsonDistance.getInt("value"); // add this line
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
The line of code will allow you to store the distance for each route. You can then get the distance using the array. For example routeDistances[0] will have the distance for the first route, routeDistances[1] will have the distance for the next route etc.

Related

MapsActivity marker won't displayed for second time

I have a MapsActivity in my app which starts by clicking on a button in MainActivity and when activity started I will get markers coordinates by JSON and show them in MapsActivity, but this will happen only in first time and once I press back and go to MainActivity and press the button again MapsActivity starts but markers won't be displayed in that . I tried to finish or destroy activity but that didn't help.
any help will be much appreciated
this is my MapsActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
map_update();
maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
final ArrayList myList;
if (checker==0) {
myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
}
else
{
checker = 0;
myList = maps;
}
mMap = googleMap;
mMap.clear();
for (int i = 0; i < myList.size(); i++) {
LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String position = "0";
String title = marker.getTitle();
for (int i = 0; i < myList.size(); i++) {
if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
position = ((ArrayList) myList.get(i)).get(0).toString();
titlename = ((ArrayList) myList.get(i)).get(1).toString();
address = ((ArrayList) myList.get(i)).get(4).toString();
}
}
foo = Integer.valueOf(position);
a = ((ArrayList) myList.get(foo)).get(0).toString();
backgroundTask = new BackgroundTask(textView);
backgroundTask.execute();
map_check = 1;
MainActivity.maps_adv = 0;
return true;
}
});
} catch (RuntimeException e) {
e.printStackTrace();
}
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
jsonobj = new JSONObject();
jsonobj.put("hotel_id_post", foo);
Log.i("EEE", a);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", "1"));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServerhotel = str.getStringFromInputStream(inputStream);
Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
HotelList.jsonroom = new JSONObject(responseServerhotel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
if (responseServerhotel.equals("{\"types\":null}"))
{
MainActivity.nothing = "no room to show";
Intent intent = new Intent(MapsActivity.this,Nothing.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(MapsActivity.this, RoomList.class);
startActivity(intent);
}
}
}
private class BackgroundTask1 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask1(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
//mMap.clear();
jsonadv = new JSONObject();
jsonadv_cont = new JSONObject();
jsonobj = new JSONObject();
jsonads = new JSONObject();
MainActivity.features = "";
features_count = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "11"));
nameValuePairs.add(new BasicNameValuePair("adv",
MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" +
features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date",
MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", num));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseServer);
jsonmap = new JSONObject(responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
if (backgroundTask1 != null) {
backgroundTask1.cancel(true);
}
if (backgroundTask2 != null) {
backgroundTask2.cancel(true);
}
finish();
}
private class BackgroundTask2 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask2(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MainActivity.url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray mapsarr = jsonmap.getJSONArray("maps");
for (int i = 0; i < mapsarr.length(); i++) {
ArrayList<Object> mapping = new ArrayList<>();
JSONObject c = mapsarr.getJSONObject(i);
String id = c.getString("hotel_id");
String name = c.getString("hotel_name");
Double x = c.getDouble("hotel_x");
Double y = c.getDouble("hotel_y");
String address = c.getString("hotel_address");
mapping.add(0, id);
mapping.add(1, name);
mapping.add(2, x);
mapping.add(3, y);
mapping.add(4, address);
maps.add(i, mapping);
}
Log.i("MAPTEST", mapsarr.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
onMapReady(mMap);
checker = 1;
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
}
public static void refresh()
{
flag = 0;
MapsActivity ma = new MapsActivity();
ma.map_update();
}

Roads googleapi: Some places missing and lines passing through edifices

I'm using the Roads Google API passing a list of positions and I want to paint lines in the most probable road driven by a car by these points.
Something is going wrong because some points are not being crossed by the lines and the lines are not using only roads, some of them pass through edifices or the sea with straight lines. I added markers to show the problem.
Is something wrong in the code?
Some sample code to get this error:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
List<LatLng> sourcePoints = new ArrayList<>();
sourcePoints.add(new LatLng(39.4321055669415, -0.343169529033198));
sourcePoints.add(new LatLng(39.4279737815806, -0.334743742804801));
sourcePoints.add(new LatLng(39.4235262880062, -0.341102620562518));
sourcePoints.add(new LatLng(39.4216973481355, -0.340624944612178));
sourcePoints.add(new LatLng(39.4194951574233, -0.335974058847626));
sourcePoints.add(new LatLng(39.4216760915054, -0.340342003540913));
sourcePoints.add(new LatLng(39.4235646246302, -0.340901154018858));
sourcePoints.add(new LatLng(39.4321131753486, -0.342995147300383));
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(sourcePoints);
polyLineOptions.width(5);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sourcePoints.get(0), 15));
List<LatLng> snappedPoints = new ArrayList<>();
new GetSnappedPointsAsyncTask().execute(sourcePoints, null, snappedPoints);
}
private String buildRequestUrl(List<LatLng> trackPoints) {
StringBuilder url = new StringBuilder();
url.append("https://roads.googleapis.com/v1/snapToRoads?path=");
for (LatLng trackPoint : trackPoints) {
url.append(String.format("%8.5f", trackPoint.latitude));
url.append(",");
url.append(String.format("%8.5f", trackPoint.longitude));
url.append("|");
}
url.delete(url.length() - 1, url.length());
url.append("&interpolate=true");
url.append(String.format("&key=%s", <your_Google_Maps_API_key>);
return url.toString();
}
private class GetSnappedPointsAsyncTask extends AsyncTask<List<LatLng>, Void, List<LatLng>> {
protected void onPreExecute() {
super.onPreExecute();
}
protected List<LatLng> doInBackground(List<LatLng>... params) {
List<LatLng> snappedPoints = new ArrayList<>();
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(buildRequestUrl(params[0]));
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder jsonStringBuilder = new StringBuilder();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
jsonStringBuilder.append(line);
jsonStringBuilder.append("\n");
}
JSONObject jsonObject = new JSONObject(jsonStringBuilder.toString());
JSONArray snappedPointsArr = jsonObject.getJSONArray("snappedPoints");
for (int i = 0; i < snappedPointsArr.length(); i++) {
JSONObject snappedPointLocation = ((JSONObject) (snappedPointsArr.get(i))).getJSONObject("location");
double lattitude = snappedPointLocation.getDouble("latitude");
double longitude = snappedPointLocation.getDouble("longitude");
snappedPoints.add(new LatLng(lattitude, longitude));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return snappedPoints;
}
#Override
protected void onPostExecute(List<LatLng> result) {
super.onPostExecute(result);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(result);
polyLineOptions.width(5);
polyLineOptions.color(Color.RED);
mGoogleMap.addPolyline(polyLineOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(result.get(0));
builder.include(result.get(result.size()-1));
LatLngBounds bounds = builder.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
}
}
}
It's everything ok with your code: there are not enough points for Snap to Roads. You should use Google Maps Directions API instead of Snap to Roads API to get lacking points: format route request, receive and parse response - you need overview_polyline tag points String value - it's encoded polyline of route part For your source points (blue path on figure):
List<LatLng> sourcePoints = new ArrayList<>();
sourcePoints.add(new LatLng(39.4321055669415, -0.343169529033198));
sourcePoints.add(new LatLng(39.4279737815806, -0.334743742804801));
sourcePoints.add(new LatLng(39.4235262880062, -0.341102620562518));
sourcePoints.add(new LatLng(39.4216973481355, -0.340624944612178));
sourcePoints.add(new LatLng(39.4194951574233, -0.335974058847626));
sourcePoints.add(new LatLng(39.4216760915054, -0.340342003540913));
sourcePoints.add(new LatLng(39.4235646246302, -0.340901154018858));
sourcePoints.add(new LatLng(39.4321131753486, -0.342995147300383));
with Google Maps Directions API implementation like that:
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = MainActivity.class.getSimpleName();
private GoogleMap mGoogleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
List<LatLng> sourcePoints = new ArrayList<>();
sourcePoints.add(new LatLng(39.4321055669415, -0.343169529033198));
sourcePoints.add(new LatLng(39.4279737815806, -0.334743742804801));
sourcePoints.add(new LatLng(39.4235262880062, -0.341102620562518));
sourcePoints.add(new LatLng(39.4216973481355, -0.340624944612178));
sourcePoints.add(new LatLng(39.4194951574233, -0.335974058847626));
sourcePoints.add(new LatLng(39.4216760915054, -0.340342003540913));
sourcePoints.add(new LatLng(39.4235646246302, -0.340901154018858));
sourcePoints.add(new LatLng(39.4321131753486, -0.342995147300383));
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(sourcePoints);
polyLineOptions.width(5);
polyLineOptions.color(Color.BLUE);
mGoogleMap.addPolyline(polyLineOptions);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sourcePoints.get(0), 15));
List<LatLng> directionsPoints = new ArrayList<>();
new GetDirectionPointsAsyncTask().execute(sourcePoints, null, directionsPoints);
}
private String buildDirectionsUrl(List<LatLng> trackPoints) {
if (trackPoints.size() < 2) {
return null;
}
final LatLng origin = trackPoints.get(0);
final LatLng dest = trackPoints.get(trackPoints.size() - 1);
StringBuilder url = new StringBuilder();
url.append("https://maps.googleapis.com/maps/api/directions/json?");
url.append(String.format("origin=%8.5f,%8.5f", origin.latitude, origin.longitude));
url.append(String.format("&destination=%8.5f,%8.5f", dest.latitude, dest.longitude));
// add waypoints, if they exists
if (trackPoints.size() > 2) {
url.append("&waypoints=");
LatLng wayPoint;
for (int ixWaypoint = 1; ixWaypoint < trackPoints.size() - 2; ixWaypoint++) {
wayPoint = trackPoints.get(ixWaypoint);
url.append(String.format("%8.5f,%8.5f|", wayPoint.latitude, wayPoint.longitude));
}
url.delete(url.length() - 1, url.length());
}
url.append(String.format("&key=%s", getResources().getString(R.string.google_maps_key)));
return url.toString();
}
private class GetDirectionPointsAsyncTask extends AsyncTask<List<LatLng>, Void, List<LatLng>> {
protected void onPreExecute() {
super.onPreExecute();
}
protected List<LatLng> doInBackground(List<LatLng>... params) {
List<LatLng> routePoints = new ArrayList<>();
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(buildDirectionsUrl(params[0]));
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder jsonStringBuilder = new StringBuilder();
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
jsonStringBuilder.append(line);
jsonStringBuilder.append("\n");
}
JSONObject jsonRoot = new JSONObject(jsonStringBuilder.toString());
JSONArray jsonRoutes = jsonRoot.getJSONArray("routes");
if (jsonRoutes.length() < 1) {
return null;
}
JSONObject jsonRoute = jsonRoutes.getJSONObject(0);
JSONObject overviewPolyline = jsonRoute.getJSONObject("overview_polyline");
String overviewPolylineEncodedPoints = overviewPolyline.getString("points");
routePoints = decodePoly(overviewPolylineEncodedPoints);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return routePoints;
}
#Override
protected void onPostExecute(List<LatLng> result) {
super.onPostExecute(result);
PolylineOptions polyLineOptions = new PolylineOptions();
polyLineOptions.addAll(result);
polyLineOptions.width(5);
polyLineOptions.color(Color.RED);
mGoogleMap.addPolyline(polyLineOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(result.get(0));
builder.include(result.get(result.size()-1));
LatLngBounds bounds = builder.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
}
}
//
// Method to decode polyline points
// Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
private List<LatLng> decodePoly(String encoded) {
List<LatLng> 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;
}
}
you get something like that (red path on figure):
NB! Don't forget to allow Directions API on Google APIs Console
More details about Direction API here and in many online tutorials/examples.

Calculating Total Distance Between Way Points android google api

I have develop an application which draws the route between start point and the destination and also user will be able to mark some waypoints along that path and the route will be drawn correctly. But I can only get the distance when I only mark 2 places on the map. If I mark 2, 3 places it will not give me the distance. These are my codes,
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;
JSONObject jDistance = null;
JSONObject jDuration = 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++){
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
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
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
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;
}
}
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("Error 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();
String distance = "";
String duration = "";
if(result.size()<1){
Toast.makeText(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){ // 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(2);
lineOptions.color(Color.RED);
}
tvDistanceDuration.setText("Distance:"+distance + ", Duration:"+duration);
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
URL I used to request
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
Error I found when I used 4 points with 2 way points
This is in onPostExecute method on lines,
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
What I have done wrong here?
You Should have to try this by using retrofit.
Put this code on button click in MainActivity:-
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, OnMapReadyCallback {
private static final String LOG_TAG = "TAG1";
private static final String KEY = "Enter Your Key";
String displayResponseSource = "";
String displayResponseDestination = "";
private Button btn_search;
private GoogleMap map;
private APIInterface apiInterface;
private SupportMapFragment mapFragment;
private AutoCompleteTextView autoCompViewSource;
private AutoCompleteTextView autoCompViewDestination;
private String autocompletetextSource = "";
private String autocompletetextDestination = "";
private LatLng maplocationdestination;
private LatLng maplocationsource;
private double longitudeSource;
private double latitudeSource;
private double latitudeDestination;
private double longitudeDestination;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompViewSource = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewSource);
autoCompViewDestination = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextViewDestination);
btn_search = (Button) findViewById(R.id.btn_search);
autoCompViewSource.setAdapter(new GooglePlacesAutocompleteAdapterSource(this, R.layout.lv_item));
autoCompViewSource.setOnItemClickListener(this);
autoCompViewDestination.setAdapter(new GooglePlacesAutocompleteAdapterDestination(this, R.layout.lv_item));
autoCompViewDestination.setOnItemClickListener(this);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
autocompletetextSource = autoCompViewSource.getText().toString();
autocompletetextDestination = autoCompViewDestination.getText().toString();
apiInterface = APIClient.getClient().create(APIInterface.class);
Call<ModelLatLong> call = apiInterface.getResponse(autocompletetextSource, KEY);
// autocompletetext,KEY
call.enqueue(new Callback<ModelLatLong>() {
#Override
public void onResponse(Call<ModelLatLong> call, Response<ModelLatLong> response) {
Log.i("TAG", response.code() + "");
ModelLatLong resource = response.body();
ArrayList<Results> resultsList = resource.getResults();
for (Results results : resultsList) {
longitudeSource = results.getGeometry().getLocation().getLng();
latitudeSource = results.getGeometry().getLocation().getLat();
Log.i("TAG1", displayResponseSource + "HI");
}
displayResponseSource = latitudeSource+ "," + longitudeSource;
// Toast.makeText(MainActivity.this, displayResponseSource, Toast.LENGTH_SHORT).show();
maplocationsource = new LatLng(latitudeSource, longitudeSource);
map.addMarker(new MarkerOptions()
.position(maplocationsource)
.snippet(autocompletetextSource)).showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLngZoom(maplocationsource, 14);
map.animateCamera(center);
}
#Override
public void onFailure(Call<ModelLatLong> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
Call<ModelLatLong> calldes = apiInterface.getResponse(autocompletetextDestination, KEY);
// autocompletetext,KEY
calldes.enqueue(new Callback<ModelLatLong>() {
#Override
public void onResponse(Call<ModelLatLong> call, Response<ModelLatLong> response) {
Log.i("TAG", response.code() + "");
ModelLatLong resourcedes = response.body();
ArrayList<Results> resultsListdes = resourcedes.getResults();
for (Results results : resultsListdes) {
longitudeDestination = results.getGeometry().getLocation().getLng();
latitudeDestination = results.getGeometry().getLocation().getLat();
Log.i("TAG1", displayResponseDestination + "HI");
}
displayResponseDestination = latitudeDestination + "," + longitudeDestination;
// Toast.makeText(MainActivity.this, displayResponseDestination, Toast.LENGTH_SHORT).show();
maplocationdestination = new LatLng(latitudeDestination, longitudeDestination);
map.addMarker(new MarkerOptions()
.position(maplocationdestination)
.snippet(autocompletetextSource)).showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLngZoom(maplocationdestination, 14);
map.animateCamera(center);
}
#Override
public void onFailure(Call<ModelLatLong> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
Call<ModelRoutes> calldistance = apiInterface.getResponseDistance(Get Your Source Latitude and Longitude Here(Eg. 20.9127766,73.7531254), Get Your Destination Latitude and Longitude Here in String(Eg. 23.0098149, 72.5035273), KEY);
calldistance.enqueue(new Callback<ModelRoutes>() {
#Override
public void onResponse(Call<ModelRoutes> call, Response<ModelRoutes> response) {
String displayResponse = "";
ModelRoutes resourcedis = response.body();
Log.i("TAG", response.code() + "Hello");
ArrayList<Routes> routesList = resourcedis.getRoutes();
for (Routes routes : routesList) {
ArrayList<Legs> legsList = routes.getLegs();
for (Legs legs : legsList) {
String killoMeter = legs.getDistance().getText();
double timeDistance = legs.getDistance().getValue();
displayResponse += "\n Killometer : " + killoMeter + "\n Time Duration : " + timeDistance + "\n";
Log.i("TAG1", displayResponse + "HI");
}
}
Toast.makeText(MainActivity.this, displayResponse, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ModelRoutes> call, Throwable t) {
Log.i("TAG1", "Failed");
call.cancel();
}
});
}
});
}
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/autocomplete/json");
sb.append("?key=Enter Your Key Here");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapterSource extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapterSource(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Object getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
class GooglePlacesAutocompleteAdapterDestination extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapterDestination(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public Object getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
resultList = autocomplete(constraint.toString());
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
ModelRoutes.java
public class ModelRoutes extends Legs {
ArrayList<Routes> routes = null;
public ArrayList<Routes> getRoutes() {
return routes;
}
public void setRoutes(ArrayList<Routes> routes) {
this.routes = routes;
}
}
Routes.java
public class Routes extends Legs{
ArrayList<Legs> legs = null;
public ArrayList<Legs> getLegs() {
return legs;
}
public void setLegs(ArrayList<Legs> legs) {
this.legs = legs;
}
}
Legs.java
public class Legs {
Distances distance;
Durations duration;
public Distances getDistance() {
return distance;
}
public void setDistance(Distances distance) {
this.distance = distance;
}
public Durations getDuration() {
return duration;
}
public void setDuration(Durations duration) {
this.duration = duration;
}
public class Distances{
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
String text;
double value;
}
public class Durations{
String text;
double value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
}
APIClient.java
public class APIClient {
private static Retrofit retrofit = null;
static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
APIInterface.java
public interface APIInterface {
#GET("/maps/api/geocode/json")
Call<ModelLatLong> getResponse(
#Query("address") String str,
#Query("key") String str2);
#GET("/maps/api/directions/json")
Call<ModelRoutes> getResponseDistance(
#Query("origin") String str,
#Query("destination") String str1,
#Query("key") String str2);
}
ModelLatLong.java
public class ModelLatLong extends Results {
private ArrayList<Results> results=null;
public ArrayList<Results> getResults() {
return results;
}
public void setResults(ArrayList<Results> results) {
this.results = results;
}
}
Results.java
public class Results extends Geometry{
private Geometry geometry;
public Geometry getGeometry() {
return this.geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
}
Geometry.java
public class Geometry extends Location{
private Location location;
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
}
Location.java
public class Location {
private double lat;
private double lng;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gmapplaceapi.MainActivity">
<AutoCompleteTextView
android:id="#+id/autoCompleteTextViewSource"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Please enter Source place"
>
<requestFocus />
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/autoCompleteTextViewDestination"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="#+id/autoCompleteTextViewSource"
android:hint="Please enter Destination place"
>
<requestFocus />
</AutoCompleteTextView>
<Button
android:id="#+id/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"
android:layout_below="#+id/autoCompleteTextViewDestination"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/btn_search"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />
</RelativeLayout>
lv_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:textSize="20dp" />
Don't forget to put Internet Permission in manifest file.

How to add TAG to every marker and set the UniqueId on every marker separatly

How to add TAG to every marker and set the UniqueId on every marker.
Uniqueid's of every marker received from the server
Here is DoInBackgroung Code please help me
for (int i = 0; i < jsonarray.length(); i++) {
// ModelClass s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), ModelClass.class);
ModelClass modelClass = new Gson().fromJson(jsonarray.getJSONObject(i).toString(), ModelClass.class);
LatLng latLng = new LatLng(Double.parseDouble(modelClass.getLatitude()), Double.parseDouble(modelClass.getLongitude())); // Use your server's methods
latLngList.add(latLng);
Here is code to add marker
private void AddPointer() {
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
OnpostExecute code where i add the Marker that received from the server in this time i have two markers on server with its uniqueId's
protected void onPostExecute(Boolean result) {
// dialog.cancel();
// adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
AddPointer();
}
Here is Model Class
public class ModelClass {
#SerializedName("longi")
public String longitudeServer;
#SerializedName("lati")
public String latitudeServer;
#SerializedName("uniqueid")
public String uniqueidSserver;
public ModelClass(){
}
public String getLongitude(){
return longitudeServer;
}
public String getLatitude(){
return latitudeServer;
}
public String getUniqueId(){
return uniqueidSserver;
}
}
Try this you can set diffrent marker and give uniqueid or name
// Prepare Model Class like this way
public class LocationDetail
{
public String longitudeServer;
public String latitudeServer;
public String uniqueidSserver;
public String getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(String longitudeServer) {
this.longitudeServer = longitudeServer;
}
public String getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(String latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
//Prepare the arraylist like this
try
{
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject
.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject
.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString(
"UniqueId").toString());
list.add(modelclass);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
//Now pass above Arraylist to method
private void showMap(ArrayList<Reach_Us> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitude();
longitude = list.get(i).getLongitude();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude())).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Pravin i do like this.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
try {
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
// JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonarray.length(); i++) {
jsonObject = jsonarray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString("UniqueId").toString());
list.add(modelclass);
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
and also
private void showMap(ArrayList<LocationDetail> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
mMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
mMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
mMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
mMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitudeServer();
longitude = list.get(i).getLongitudeServer();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitudeServer(), list
.get(i).getLongitudeServer()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And also in
public class LocationDetail
{
public double longitudeServer;
public double latitudeServer;
public String uniqueidSserver;
public double getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(double longitudeServer) {
this.longitudeServer = longitudeServer;
}
public double getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(double latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
But error in this line
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build(); it shows LatLnd Double Double cannot be applied to Double

Google map drow route between current location and point

I'm trying to draw a route between the current location and another point. I wrote code which can check the current location and also put the point on the map on a map click. At the moment, the program is working perfectly,
but I want to draw another route between the current location and a new point( point witch I added map on Map click listener).
My code is below, does anyone know how I can to add this logic on my code?
public class GPS extends Activity implements
OnMyLocationChangeListener,OnMapClickListener,
OnMapLongClickListener, OnMarkerDragListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Circle myCircle;
Location myLocation;
TextView tvLocInfo, GPSLocation;
LatLng latLng;
boolean markerClicked;
ArrayList<LatLng> markerPoints;
Polygon polygon;
public Button btnline;
double Clicklatitude, Clicklongitude, latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gps);
markerPoints=new ArrayList<LatLng>();
btnline = (Button) findViewById(R.id.button1);
tvLocInfo = (TextView) findViewById(R.id.GpsTxt);
GPSLocation = (TextView) findViewById(R.id.GPSLocation);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment = (MapFragment) myFragmentManager
.findFragmentById(R.id.GpsMap);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerDragListener(this);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
markerClicked = false;
btnline.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onMyLocationChange(Location location) {
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
myMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
GPSLocation.setText(latitude + " " + longitude);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng locLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
double accuracy = location.getAccuracy();
if (myCircle == null) {
CircleOptions circleOptions = new CircleOptions().center(locLatLng)
// set center
.radius(accuracy)
// set radius in meters
.fillColor(Color.RED).strokeColor(Color.BLACK)
.strokeWidth(5);
myCircle = myMap.addCircle(circleOptions);
} else {
myCircle.setCenter(locLatLng);
myCircle.setRadius(accuracy);
}
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// myMap.animateCamera(CameraUpdateFactory.newLatLng(locLatLng));
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMapLongClick(LatLng point) {
}
#Override
public void onMapClick(LatLng point) {
Clicklatitude = point.latitude;
Clicklongitude = point.longitude;
tvLocInfo.setText(Clicklatitude + " " + Clicklongitude);
if (point != null)
myMap.clear();
myMap.addMarker(new MarkerOptions().position(point).draggable(true));
markerClicked = false;
}
}
I want to get a like this result enter link description here
I achieved same thing via this code. This will be some different Code from what you have tried.
First of all Implement your class with this two things
implements OnMapReadyCallback,LocationListener
When you implement OnMapReadyCallback you will get pre-define method called
"OnMapReady"
#Override
public void onMapReady(GoogleMap googleMap) {
destiLati = 40.728634;
destiLong = -73.974956;
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
// Add a marker in Destination/Desire point and move the camera
DestinationPoint = new LatLng(destiLati, destiLong);
mMap.addMarker(new MarkerOptions().position(DestinationPoint).title("Destination
Point")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
//To move camera to Desination Location.
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DestinationPoint, 10));
//Permission To get Current Location
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
To get current location I have made one method and when you implement LocationListener
it will give you pre-define method called "onLocationChanged"
private void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
//This thing will get User's current location
originLati = location.getLatitude();
originLong = location.getLongitude();
exeTask();
//Log.d(originLati.toString(),"This is the value of orginalati" + originLati.toString() + " " + originLong.toString());
}
To get path between Your current location and destination..
you need to pass data to google API it will write one JSON result
you have to get this result and show it into Polyline(to display path)
private void exeTask(){
String originPl = "origin=" + originLati.toString() + "," + originLong.toString();
String destipl = "destination=" + destiLati.toString() + "," + destiLong.toString();
String sensor = "sensor-false";
String mode = "mode-driving";
String param = originPl + "&" + destipl + "&" + sensor + "&" + mode + "&key='Your_API_KEY'";
final_url = "https://maps.googleapis.com/maps/api/directions/json?" + param;
//Log.d(final_url,"This is the URL which was created");
TaskRequestDirections taskRequestDirections = new TaskRequestDirections();
taskRequestDirections.execute(final_url);
}
private String requestDirection(String reqUrl) throws IOException {
String responseString = "";
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try{
URL url = new URL(reqUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
//TO get the in String format response result
inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
responseString = stringBuffer.toString();
bufferedReader.close();
inputStreamReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
httpURLConnection.disconnect();
}
return responseString;
}
public class TaskRequestDirections extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String responseString = "";
try {
responseString = requestDirection(strings[0]);
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//Parse json/ Data will come from here..
TaskParser taskParser = new TaskParser();
taskParser.execute(s);
}
}
public class TaskParser extends AsyncTask<String, Void, List<List<HashMap<String, String>>> > {
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jsonObject = null;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(strings[0]);
DirectionsParser directionsParser = new DirectionsParser();
routes = directionsParser.parse(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
//To get list route and display it into the map
ArrayList points = null;
PolylineOptions polylineOptions = null;
for (List<HashMap<String, String>> path : lists) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
for (HashMap<String, String> point : path) {
double lat = Double.parseDouble(point.get("lat"));
double lon = Double.parseDouble(point.get("lon"));
points.add(new LatLng(lat,lon));
}
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.BLUE);
polylineOptions.geodesic(true);
}
if (polylineOptions!=null) {
mMap.addPolyline(polylineOptions);
} else {
//Toast.makeText(getApplicationContext(), "Direction not found!", Toast.LENGTH_SHORT).show();
}
}
}
And finally call this pre-define Class as it show here to decode polylines and get json array result
public class DirectionsParser {
/**
* Returns a list of lists containing latitude and longitude from a JSONObject
*/
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");
// Loop for all routes
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
//Loop for all legs
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
//Loop for all steps
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List list = decodePolyline(polyline);
//Loop for 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("lon", 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
* Source : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
*/
private List decodePolyline(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;
}
}
Hope This help :)

Categories

Resources