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.
Related
I need to extract values from the api of a city to a class in my own project.
This is the class i want to convert to.
public class Parada {
#SerializedName("wgs84_pos:long")
private long lon;
#SerializedName("wgs84_pos:lat")
private long lat;
#SerializedName("ayto:parada")
private String parada;
#SerializedName("vivo:address1")
private String direccion;
}
public class Santander {
private List<Result> results;
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
This is my code.
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://datos.santander.es/api/datos/paradas_bus.json");
httpGet.setHeader("content-type", "application/json");
HttpResponse resp = httpClient.execute(httpGet);
String respStr = EntityUtils.toString(resp.getEntity());
Gson gson = new GsonBuilder().create();
Santander santander = gson.fromJson(respStr, Santander.class);
List<Parada> paradas=new ArrayList<Parada>();
for (Parada p : santander.getResults())
{
paradas.add(p);
}
return paradas;
}
catch(Exception ex)
{
Log.e("ServicioRest", "Error!", ex);
}
Toast.makeText(getApplicationContext(), "Error grabbing values, return is null", Toast.LENGTH_LONG).show();
return null;
}
protected void onPostExecute(List<Parada> lParadas) {
if (lParadas!=null&&lParadas.size()>0) {
paradas=new Parada[lParadas.size()];
for (int i = 0; i < paradas.length; ++i){
paradas[i]=lParadas.get(i);
}
}
}
I need to get coordinates, address and name from the api into the array to then add them as points in a map, which is in a separate activity.
It gets the data in respStr but it doesnt go into class Santander
I dont think this is important but i add the code i use for the map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Parada[] paradas=MainActivity.paradas;
if (paradas!=null&¶das.length>0) {
List<MarkerOptions> marcadores=new ArrayList<MarkerOptions>();
for (int i = 0; i < paradas.length; ++i) {
Parada p=paradas[i];
LatLng pCoords = new LatLng(p.getLat(), p.getLon());
marcadores.add(new MarkerOptions().position(pCoords).title(p.getParada()));
}
}
// Add a marker in Sydney and move the camera
LatLng ayto = new LatLng(43.461, -3.80793);
mMap.moveCamera(CameraUpdateFactory.newLatLng(ayto));
}
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.
I have spent days on this, but I can't find a solution to my problem:
I'm developing an app that retrieves a list of theaters showing some movie selected by the user, parsing an HTML page in an AsyncTask.
I want to visualize those theaters on a Map with markers, so I need coordinates: once the "GetCinemaList" AsyncTask is completed, I try to populate my markerList in onPostExecute.
I have an SQLite db in which I store [theater|city|lat|lng]. So I first look up in the db, if it is not found I want call another AsyncTask to retrieve coordinates from HTTP google geocoding ('cause device geocoder returns null, causing the app to crash)
The problem is I am not able to return the LatLng point to the first AsyncTask...
I have tried to use listeners and to override processFinish(LatLng p), but I can't assign the value to my variable cause, accessing it from inner class it should be final.
Any help/idea? Thanks!
Here my code (containing error) for the AsyncTasks , in my Activity.
private class GetCinemaList extends AsyncTask<URL, Void, List<String>> {
private Context mContext;
public GetCinemaList(Context c){
mContext = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
List<String> cinemas = new ArrayList<>();
Document docHTML = null;
try {
docHTML = QueryUtils.makeRequest(urls[0]);
cinemas = QueryUtils.extractCinemasFromHTML(mTitile, docHTML);
} catch (IOException e) {
Log.e("JSwa", "Problem making request for parsing HTML "+e);
}
return cinemas;
}
#Override
protected void onPostExecute(List<String> result) {
super.onPostExecute(result);
cinemaList = result;
LatLng point;
pointList = new ArrayList<>();
for (String elem : cinemaList) {
String name = elem.split("\t")[0];
String orari = elem.split("\t")[1];
Cursor cursor = queryDB(mCinemaDbR, city, name);
if (!cursor.moveToFirst()) {
// call geocoding service
new LatLongFromService(name.concat(" " + city), new AsyncResponse() {
#Override
public void processFinish(LatLng output) {
point = output;
}
}).execute();
Log.d("JSwa", "Inserting point "+point.toString());
// insert new value in the database
long id = addCimena(mCinemaDbW, name, city, String.valueOf(point.latitude), String.valueOf(point.longitude));
// insert new value in the list
MarkerOptions marker = new MarkerOptions().position(point).title(name).snippet(orari);
pointList.add(marker);
}
else{
double lat = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LAT)));
double lng = Double.parseDouble(cursor.getString(cursor.getColumnIndex(CinemaEntry.COLUMN_LNG)));
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat,lng)).title(name)
.snippet(orari);
pointList.add(marker);
}
cursor.close();
}
for (MarkerOptions marker : pointList){
m_map.addMarker(marker);
}
}
}
// Sometimes happens that device gives location = null
public class LatLongFromService extends AsyncTask<Void, Void, StringBuilder> {
String place;
public AsyncResponse delegate = null;
public LatLongFromService(String place, AsyncResponse resp) {
this.place = place;
delegate = resp;
}
#Override
protected StringBuilder doInBackground(Void... params) {
try {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + this.place + "&sensor=false";
URL url = new URL(googleMapUrl);
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);
}
return jsonResults;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(StringBuilder result) {
super.onPostExecute(result);
try {
JSONObject jsonObj = new JSONObject(result.toString());
JSONArray resultJsonArray = jsonObj.getJSONArray("results");
JSONObject location = resultJsonArray
.getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
String lat_helper = location.getString("lat");
double lat = Double.valueOf(lat_helper);
String lng_helper = location.getString("lng");
double lng = Double.valueOf(lng_helper);
delegate.processFinish(new LatLng(lat, lng));
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
I'm using google maps to show some markers. The markers are download from a database and, at the same time, I get the distancematrix from google api, between the current position of the user and the marker that I get from the database.
My problem is that I was doing this with .get, bloking my ui (I've read that .get blocked the ui:
dataFromAsyncTask = testAsyncTask.get();
Now, I'm trying to do the same without blocking the ui, but I'm not be able to get at the same time, or in a good way, the distance for this markers.
I appreciate some help, please.
This is my code with my old and wrong .get:
for (City city : listCity.getData()) {
geoPoint = city.getLocation();
nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
startRetrievenDistanceAndDuration();
try {
dataFromAsyncTask = testAsyncTask.get();
} catch (InterruptedException i) {
} catch (ExecutionException e) {
}
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameCity)
.snippet(dataFromAsyncTask)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
startRetrievenDistanceAndDuration method:
private void startRetrievenDistanceAndDuration() {
final String url;
testAsyncTask = new DistanceBetweenLocations(new FragmentCallback() {
#Override
public void onTaskDone(String result) {
}
});
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";
testAsyncTask.execute(new String[]{url});
}
public interface FragmentCallback {
public void onTaskDone(String result);
AsyncTask class:
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url=new URL(params[0]);
}catch (MalformedURLException m){
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
}catch (IOException e){}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
}catch (IOException e){
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return distance + ", " + duration;
}
#Override
protected void onPostExecute(String result) {
mFragmentCallback.onTaskDone(result);
}
}
I'm trying to do this, but I only show the last marker of my list:
Call in the loop the method:
startRetrievenDistanceAndDuration();
And in onTaskDone try to put the marker, but only get the last marker of my list
#Override
public void onTaskDone(String result) {
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(result)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
UPDATED AFTER CHANGES: (still don't work)
I can parse the data in Asynctask and send it in onPostExecute, but I only get one value, and not the 9 values that I have....
MAIN ACTIVITY:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(HashMap<String, String> result) {
super.onPostExecute(result);
String name = result.get("beachName");
String distance = result.get("distance");
String duration = result.get("duration");
String latitue = result.get("latitude");
String longitude = result.get("longitude");
Double mlatituDouble = Double.parseDouble(latitue);
Double mlongitudeDouble = Double.parseDouble(longitude);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
Toast.makeText(getActivity(), "mMap NO null", Toast.LENGTH_SHORT).show();
mMap.addMarker(new MarkerOptions().position(new LatLng(mlatituDouble, mlongitudeDouble))
.title(name)
.snippet(distance + " " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
ASYNCTASK CLASS:.
public class DistanceBetweenLocations extends AsyncTask<String, String, HashMap<String, String>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
HashMap<String, String> map;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected HashMap<String, String> doInBackground(String... params) {
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
map = new HashMap<String, String>();
map.put("beachName", nameBeach);
map.put("distance", distance);
map.put("duration", duration);
map.put("latitude", latitude);
map.put("longitude", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return map;
}
}
I'll use your last code (the "UPDATED AFTER CHANGES"), ok?
If I get it right, your DistanceBetweenLocations result will be a list of beaches geolocation data. So, on every iteration of the for loop in doInBackground, you are replacing the value of "map" variable, this is your problem.
To solve your problem, you can have a List of HashMap or a List of a Pojo like this:
public class BeachPojo {
private String beachName;
private String distance;
private String duration;
private String latitude;
private String longitude;
public String getBeachName() {
return beachName;
}
public void setBeachName(String beachName) {
this.beachName = beachName;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
Using the Pojo, your AsyncTask will be like this:
public class DistanceBetweenLocations extends AsyncTask<String, String, List<BeachPojo>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected List<BeachPojo> doInBackground(String... params) {
List<BeachPojo> list = new ArrayList<BeachPojo>();
BeachPojo pojo;
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
pojo = new BeachPojo();
pojo.setBeachName(nameBeach);
pojo.setDistance(distance);
pojo.setDuration(duration);
pojo.setLatitude(latitude);
pojo.setLongitude(longitude);
list.add(pojo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return list;
}
}
Now you have a List to iterate. I have adjusted the code a little bit to this goal:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(List<BeachPojo> result) {
super.onPostExecute(result);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
}
Double beachLatitude;
Double beachLongitude;
for (BeachPojo pojo : result) {
beachLatitude = Double.parseDouble(pojo.getLatitude());
beachLongitude = Double.parseDouble(pojo.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(beachLatitude, beachLongitude))
.title(pojo.getBeachName())
.snippet(pojo.getDistance() + " " + pojo.getDuration())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
I hope you understand the idea of returning a List from your AsyncTask and loop throught the result on onPostExecute method.
Note: this is an implementation without knowing the real code, then you should adjust to your reality.
I'm not exactly sure what you're trying to do but I think you've made this more complicated then it has to be.
From what I understand you have a list of City objects and you use them to construct some URLs from which you retrieve a JSON object that is use to construct MarkerOptions objects.
You can do that using a AsyncTask like this:
public class Task extends AsyncTask<City, Void, Markers> {
String currentLatitude;
String currentlongitude;
public Task(String currentLatitude, String currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected String doInBackground(City... cities) {
final Markers mMap = ...;
for (City city : cities) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint != null) {
String latitude = String.valueOf(geoPoint.getLatitude());
String longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";);
urlConnection = (HttpURLConnection) url.openConnection();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString()).getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0);
String duration = jsonObject.getJSONObject("duration").getString("text");
String distance = jsonObject.getJSONObject("distance").getString("text");
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(distance + ", " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (urlConnection != null) {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return mMap;
}
}
And here is how you can use this task.
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Task task = new Task(currentLatitude, currentlongitude){
#Override
protected void onPostExecute(Markers markers) {
super.onPostExecute(markers);
//This runs on the UI thread and "markers" is the "mMap" object that was create on the background thread.
}
};
List<City> cities = ....
task.execute(cities.toArray(new City[cities.size()]));
}
}
The idea is that you need to execute all the long running operation in the AsyncTask's doInBackground(...) method. Also, you don't need to create other objects to deal with the AsyncTask response, you can override the task's onPostExecute(...) inside the class you've created the task in.
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 :)