How to separate main route and alternate routes' polyline google map android? - android

I noticed that my main route and alternate route are connected that when I set an onclick to it, example I just want to change my main route's color to blue, the alternate route also changes to blue. How to separate them so I can change alternate routes' and main route's colors?
This is my Fragment.java
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 = "AIzaSyAYyvjDnsqEFVhnDflaruaTAChEzkPxpsA";
/**************************************************************/
//FOR COLLAPSING TOOLBAR
private CollapsingToolbarLayout collapsingToolbarLayout = null;
/***************************************************************/
//**********For changing colors in the directions************************************************************/
/**************************************************************************************************************/
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();
List<Route> gRoute = new ArrayList<Route>();
Route rr = new Route();
gRoute.add(rr);
List<Route> nRoute;
nRoute = routes;
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (int i = 0; i < gRoute.size(); i++)
{
Toast.makeText(getActivity(), "" +gRoute.size()+ "Shortest Route Found...", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "" +nRoute.size()+ "Route Found...", Toast.LENGTH_SHORT).show();
}
for (final Route distance : routes)
{
Toast.makeText(getActivity(), "Distance: " + distance.distance.text, Toast.LENGTH_SHORT).show();
}
Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
// ((TextView) Myview.findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text);
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);
}
});
/*************************************************************************************************/
Random rnd = new Random();
//int color = Coor.argb(255, 112, 112, 112);
//int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258));
int color = Color.parseColor("blue");
// #999999 grey
/**/
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));
}
}
My directionfinder.java
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;
}
}
Route.java
public class Route {
public Distance distance;
public Duration duration;
public String endAddress;
public LatLng endLocation;
public String startAddress;
public LatLng startLocation;
public List<LatLng> points;
}
Duration.java
public class Duration {
public String text;
public int value;
public Duration(String text, int value) {
this.text = text;
this.value = value;
}
}
Distance.java
public class Distance {
public String text;
public int value;
public Distance(String text, int value) {
this.text = text;
this.value = value;
}
}
DirectionFinderListener.java
public interface DirectionFinderListener {
void onDirectionFinderStart();
void onDirectionFinderSuccess(List<Route> route);
}

In the for loop:
for (Route route : routes) {
You set the color here:
int color = Color.parseColor("blue");
This int doesn't change value when your app is drawing the polylines for each route. If you want different colors for different polylines, you will need to make changes so that this variable's value changes. For example, you could have a counter initially set to 0 in the for loop that increments each time a polyline is drawn. You could then add a conditional to set the color depending on what the count is. I'll rewrite your onDirectionsFinderSuccess function:
#Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
int count = 0; //counter for your for each loop
int color = Color.parseColor("blue"); //moving this here to the beginning of your function
List<Route> gRoute = new ArrayList<Route>();
Route rr = new Route();
gRoute.add(rr);
List<Route> nRoute;
nRoute = routes;
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (int i = 0; i < gRoute.size(); i++)
{
Toast.makeText(getActivity(), "" +gRoute.size()+ "Shortest Route Found...", Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "" +nRoute.size()+ "Route Found...", Toast.LENGTH_SHORT).show();
}
for (final Route distance : routes)
{
Toast.makeText(getActivity(), "Distance: " + distance.distance.text, Toast.LENGTH_SHORT).show();
}
Toast.makeText(getActivity(), "Directions found!", Toast.LENGTH_SHORT).show();
for (Route route : routes) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
// ((TextView) Myview.findViewById(R.id.tvDuration)).setText(route.duration.text);
((TextView) Myview.findViewById(R.id.tvDistance)).setText(route.distance.text);
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);
}
});
/*************************************************************************************************/
Random rnd = new Random();
//int color = Coor.argb(255, 112, 112, 112);
//int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(257), rnd.nextInt(258));
if(count == 0)
color = Color.parseColor("blue");
else if(count == 1)
color = Color.parseColor("red");
else
color = Color.parseColor("green");
//I only did this for 3 routes, but you can continue to follow this logic to color each route differently.
// #999999 grey
/**/
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));
count++;
}
}
I hope this helps!

Related

App Crashing while Reopening Fragment

Hello Everyone My app is getting crashed when the tabs are opened randomly and it is giving error like this in my logcat can any one help me in fixing this
In this fragment I integrated Displaying map information in Listview header for that I'm using SupportMapFragment
Here Is my following code
public class ChainTab extends Fragment implements ResponseListner, OnMapReadyCallback, LocationListener, GoogleMap.OnMarkerClickListener {
String TAG = ChainTab.class.getSimpleName();
String bottleId;
String url;
ListView bottleChainListView;
// NonScrollListView bottleChainListView;
Context context;
View rootView;
String responseVal;
private GoogleMap mMap;
private LocationManager mLocationManager = null;
private String provider = null;
private Marker mCurrentPosition = null;
ProgressDialog PD;
private List<BottleInfoModel> bottleInfoModelList;
private List<CreatedAt> createdAtList;
private List<UpdatedAt> updatedAtList;
private List<Scans> scansList;
private Polyline mPolyline = null;
private LatLng mSourceLatLng = null;
private LatLng mDestinationLatLng = null;
TextView serialNoTV, entityNameTV, productTypeChainTV, originTV, getQTYUOM, entityType;
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.chain_tab, viewGroup, false);
bottleInfoModelList = new ArrayList<>();
createdAtList = new ArrayList<CreatedAt>();
updatedAtList = new ArrayList<>();
scansList = new ArrayList<>();
context = getActivity();
bottleChainListView = rootView.findViewById(R.id.bottleChainListView);
return rootView;
}
public void displayMsgs(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0)
return;
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
Log.i(TAG,"NFC Id Value is :: "+builder.toString().trim());
// fab.setVisibility(View.VISIBLE);
// bottleSerialNo = textVal.getText().toString().trim();
// bottleSerialNo = "testing";
ServerHit serverHit = new ServerHit();
// url = AppConfig.REGISTER_BOTTLE_INFO + "/" + builder.toString().trim();
url = AppConfig.REGISTER_BOTTLE_INFO + "/" + "testing";
if(context != null)
serverHit.getScannedBottleInfo(context, url, this);
else
Log.i(TAG, "Context Value is Null....154");
}
#Override
public String onResponse(String response) {
responseVal = response;
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONObject payloadObject = jsonObject.getJSONObject("payload");
// for (int i =0; i<payloadObject.length(); i++){
JSONArray jsonArray = payloadObject.getJSONArray("scans");
BottleInfoModel bottleInfoModel = new BottleInfoModel();
bottleInfoModel.setEntityName(payloadObject.getString("entityName"));
bottleInfoModel.setEntityType(payloadObject.getString("entityType"));
JSONObject createdDateObj = payloadObject.getJSONObject("created_at");
CreatedAt createdAt = new CreatedAt();
createdAt.setDate(createdDateObj.getString("date"));
createdAtList.add(createdAt);
bottleInfoModel.setCreatedAtList(createdAtList);
for (int j = 0; j <= jsonArray.length() - 1; j++) {
JSONObject jsonObjectScan = jsonArray.getJSONObject(j);
Scans scansModel = new Scans();
scansModel.setEntityType(jsonObjectScan.getString("entityType"));
scansModel.setEntityName(jsonObjectScan.getString("entityName"));
scansModel.setCreated_at(jsonObjectScan.getString("created_at"));
scansModel.setLat(jsonObjectScan.getString("lat"));
scansModel.setLongVal(jsonObjectScan.getString("long"));
scansList.add(scansModel);
}
bottleInfoModel.setScansList(scansList);
bottleInfoModelList.add(bottleInfoModel);
// LayoutInflater inflater = getLayoutInflater();
// View viewGroup = inflater.inflate(R.layout.chaintab_lv_header, bottleChainListView, false);
LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.chaintab_lv_header,bottleChainListView, false);
// viewLand=inflater.inflate(R.layout.activity_main_land,null);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.fragment_track_order_map_fragment);
mapFragment.getMapAsync(this);
entityNameTV = (TextView) view.findViewById(R.id.entityNameTV);
serialNoTV = (TextView) view.findViewById(R.id.serialNoTV);
entityType = (TextView) view.findViewById(R.id.entityType);
getQTYUOM = (TextView) view.findViewById(R.id.getQTYUOM);
originTV = (TextView) view.findViewById(R.id.originTV);
productTypeChainTV = (TextView) view.findViewById(R.id.productTypeChainTV);
entityNameTV.setText(payloadObject.getString("entityName"));
serialNoTV.setText("#" + payloadObject.getString("serialNumber"));
entityType.setText(payloadObject.getString("entityType"));
getQTYUOM.setText(payloadObject.getString("qtyUOM"));
productTypeChainTV.setText(payloadObject.getString("productDescription"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
formatter = new SimpleDateFormat("MMMM yyyy");
String mainChapterNumber = createdDateObj.getString("date").split("\\.", 2)[0];
Log.i("Value iss....", "Value is :: " + mainChapterNumber);
Date date = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = format.parse(mainChapterNumber);
} catch (ParseException e) {
e.printStackTrace();
}
String originStr = null, dateStr = null;
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(payloadObject.getString("origin") + " " + formatter.format(date));
if (matcher.find()) {
originStr = payloadObject.getString("origin");
dateStr = formatter.format(date).toString().trim();
}
originStr = setMultiColor(originStr, "#363636");
dateStr = setMultiColor(dateStr, "#87CEFA");
originTV.setText(Html.fromHtml(originStr + " " + dateStr));
ChainItemsAdapter chainItemsAdapter = new ChainItemsAdapter(context, scansList);
// ViewGroup header = (ViewGroup)inflater.inflate(R.layout.chaintab_lv_header,bottleChainListView,false);
bottleChainListView.addHeaderView(view);
bottleChainListView.setAdapter(chainItemsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
// This block is used while implementing the things with chain api url link
/*
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray payloadJsonArray = jsonObject.getJSONArray("payload");
for (int i=0; i<payloadJsonArray.length(); i++){
BottleInfoModel bottleInfoModel = new BottleInfoModel();
JSONObject payloadJOBJ = payloadJsonArray.getJSONObject(i);
bottleInfoModel.setLongVal(payloadJOBJ.getString("long"));
bottleInfoModel.setLatVal(payloadJOBJ.getString("lat"));
bottleInfoModel.setEntityName(payloadJOBJ.getString("entityName"));
bottleInfoModel.setSerialNumber(payloadJOBJ.getString("bottleId"));
CreatedAt createdAt = new CreatedAt();
JSONObject jsonObjectCreatedAt = payloadJOBJ.getJSONObject("created_at");
createdAt.setDate(jsonObjectCreatedAt.getString("date"));
createdAt.setTimezone(jsonObjectCreatedAt.getString("timezone"));
createdAt.setTimezone_type(jsonObjectCreatedAt.getString("timezone_type"));
createdAtList.add(createdAt);
bottleInfoModel.setCreatedAtList(createdAtList);
bottleInfoModelList.add(bottleInfoModel);
}
entityNameTV.setText(bottleInfoModelList.get(0).getEntityName());
serialNoTV.setText(bottleInfoModelList.get(0).getSerialNumber());
ChainItemsAdapter chainItemsAdapter = new ChainItemsAdapter(context, bottleInfoModelList);
bottleChainListView.setAdapter(chainItemsAdapter);;
}catch (JSONException e){
e.printStackTrace();
}*/
return null;
}
private String setMultiColor(String text, String color) {
String input = "<font color=" + color + ">" + text + "</font>";
return input;
}
#Override
public JSONObject onResponse(JSONObject response) {
return null;
}
#Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
case LocationProvider.AVAILABLE:
break;
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// LatLng target = mMap.getCameraPosition().target;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
addMarks(mMap);
if (isProviderAvailable() && (provider != null)) {
locateCurrentPosition();
}
}
private void locateCurrentPosition() {
int status = context.getPackageManager().checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
context.getPackageName());
if (status == PackageManager.PERMISSION_GRANTED) {
Location location = mLocationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
// mLocationManager.addGpsStatusListener(this);
long minTime = 5000;// ms
float minDist = 5.0f;// meter
mLocationManager.requestLocationUpdates(provider, minTime, minDist,
this);
}
}
private void updateWithNewLocation(Location location) {
if (location != null && provider != null) {
double lng = location.getLongitude();
double lat = location.getLatitude();
mSourceLatLng = new LatLng(lat, lng);
// addBoundaryToCurrentPosition(lat, lng);
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(8).build();
// mMap.getCameraPosition().target
// if (mMap != null)
// mMap.animateCamera(CameraUpdateFactory
// .newCameraPosition(camPosition));
} else {
Log.d("Location error", "Something went wrong");
}
}
private void addBoundaryToCurrentPosition(double lat, double lang) {
MarkerOptions mMarkerOptions = new MarkerOptions();
mMarkerOptions.position(new LatLng(lat, lang));
mMarkerOptions.icon(BitmapDescriptorFactory
.fromResource(R.mipmap.ic_launcher));
mMarkerOptions.anchor(0.5f, 0.5f);
CircleOptions mOptions = new CircleOptions()
.center(new LatLng(lat, lang)).radius(10000)
.strokeColor(0x110000FF).strokeWidth(1).fillColor(0x110000FF);
mMap.addCircle(mOptions);
if (mCurrentPosition != null)
mCurrentPosition.remove();
mCurrentPosition = mMap.addMarker(mMarkerOptions);
}
private boolean isProviderAvailable() {
mLocationManager = (LocationManager) context.getSystemService(
Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mLocationManager.getBestProvider(criteria, true);
if (mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
return true;
}
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
return true;
}
if (provider != null) {
return true;
}
return false;
}
private void addMarks(GoogleMap mMap) {
// displayResponseVal(responseVal);
List<LatLng> latLngsList = new ArrayList<>();
mMap = mMap;
Polyline polylineOptions = null;
LatLng latLng = null;
// for (int i = 0; i < bottleInfoModelList.size(); i++) {
for (int i = 0; i < scansList.size(); i++) {
Scans scanInfoModel = scansList.get(i);
double latval, longVal;
try {
latval = Double.parseDouble(scanInfoModel.getLat());
longVal = Double.parseDouble(scanInfoModel.getLongVal());
} catch (NumberFormatException e) {
e.printStackTrace();
latval = 0;
longVal = 0;
}
latLng = new LatLng(latval, longVal);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(scanInfoModel.getEntityName());
mMap.addMarker(markerOptions);
mMap.setOnMarkerClickListener((GoogleMap.OnMarkerClickListener) this);
latLngsList.add(latLng);
}
drawRouteOnMap(mMap, latLngsList);
}
private void drawRouteOnMap(GoogleMap mMap, List<LatLng> latLngsList) {
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
options.addAll(latLngsList);
Polyline polyline = mMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latLngsList.get(0).latitude, latLngsList.get(0).longitude))
.zoom(8)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
}
It corresponding log error
FATAL EXCEPTION: main
Process: winepoc.tw.net.winepoc, PID: 17576
java.lang.IllegalStateException: onGetLayoutInflater() cannot be executed until the Fragment is attached to the FragmentManager.
at android.support.v4.app.Fragment.getLayoutInflater(Fragment.java:1249)
at android.support.v4.app.Fragment.onGetLayoutInflater(Fragment.java:1201)
at android.support.v4.app.Fragment.performGetLayoutInflater(Fragment.java:1231)
at android.support.v4.app.Fragment.getLayoutInflater(Fragment.java:1217)
at winepoc.tw.net.winepoc.fragments.ChainTab.onResponse(ChainTab.java:199)
\at winepoc.tw.net.winepoc.ServerHit$3.onResponse(ServerHit.java:80)
at winepoc.tw.net.winepoc.ServerHit$3.onResponse(ServerHit.java:71)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Activity activity = getActivity();
if(activity != null){
// etc ...
}
try this i think your activity is null in coding

How to show infowindow without cluster click

I have little problem of Cluster and Custom InfoWindow.
I don't want to show Infowindow when i click cluster.
But my application is show Infowindow when i click clusterItem and click Cluter. It show last click ClusterItem's Infowindow.
Code :
public class MapsLActivity extends FragmentActivity implements OnMapReadyCallback, ClusterManager.OnClusterItemClickListener<House>, GoogleMap.OnMapClickListener, ClusterManager.OnClusterClickListener<House>{
private GoogleMap mMap;
private View infoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_k);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
ClusterManager<House> mClusterManager = new ClusterManager<>(this, mMap);
mMap.setOnMapClickListener(this);
mMap.setOnMarkerClickListener(mClusterManager);
mMap.setOnCameraChangeListener(mClusterManager);
AssetManager assetManager = getResources().getAssets();
try {
AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("yb_edu.json");
BufferedReader br = new BufferedReader(new InputStreamReader(ais));
StringBuilder sb = new StringBuilder();
int bufferSize = 1024 * 1024;
char readBuf[] = new char[bufferSize];
int resultSize = 0;
while ((resultSize = br.read(readBuf)) != -1) {
if (resultSize == bufferSize) {
sb.append(readBuf);
} else {
for (int i = 0; i < resultSize; i++) {
sb.append(readBuf[i]);
}
}
}
String jString = sb.toString();
JSONObject object = new JSONObject(jString);
JSONArray list = new JSONArray(object.getString("yb_edu"));
for (int i = 0; i < list.length(); i++) {
JSONObject inside = list.getJSONObject(i);
String title = inside.getString("title");
String lats = inside.getString("lat");
String lngs = inside.getString("lng");
double lat = Double.parseDouble(lats);
double lng = Double.parseDouble(lngs);
LatLng position = new LatLng(lat, lng);
Log.v("###", "postion : " + position);
Log.v("##i=##", String.valueOf(i));
i++;
mClusterManager.addItem(new House(position, title));
}
mClusterManager.cluster(); //클러스터 새로고침
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mClusterManager.setOnClusterItemClickListener(this);
mClusterManager.setOnClusterClickListener(this);
}
#Override
public boolean onClusterItemClick(final House house) {
Toast.makeText(this, "onClusterItemClick", Toast.LENGTH_SHORT).show();
LatLng latLng = house.getLatLng();
Log.v("##", "LatLng : " + latLng);
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(house.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(house.getLatLng().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
#Override
public boolean onClusterClick(Cluster<House> cluster) {
mMap.moveCamera(CameraUpdateFactory.zoomIn());
Toast.makeText(this, "onClusterClick", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMapClick(LatLng latLng) {
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
Finally i resolve it....
public class MapsPActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnCameraMoveListener {
private GoogleMap mMap;
private float pastZoom = 0;
private ArrayList<House> edulList;
private int clusters = 0;
private int marks = 0;
private View infoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_m);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
edulList = new ArrayList<>();
addEdu();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
mMap.setOnCameraMoveListener(this);
}
private void addEdu() {
try {
AssetManager assetManager = getResources().getAssets();
AssetManager.AssetInputStream ais = (AssetManager.AssetInputStream) assetManager.open("list.json");
BufferedReader br = new BufferedReader(new InputStreamReader(ais));
StringBuilder sb = new StringBuilder();
int bufferSize = 1024 * 1024;
char readBuf[] = new char[bufferSize];
int resultSize = 0;
while ((resultSize = br.read(readBuf)) != -1) {
if (resultSize == bufferSize) {
sb.append(readBuf);
} else {
for (int i = 0; i < resultSize; i++) {
sb.append(readBuf[i]);
}
}
}
String jString = sb.toString();
JSONObject object = new JSONObject(jString);
JSONArray list = new JSONArray(object.getString("list"));
for (int i = 0; i < list.length(); i++) {
JSONObject inside = list.getJSONObject(i);
String title = inside.getString("title");
String lats = inside.getString("lat");
String lngs = inside.getString("lng");
double lat = Double.parseDouble(lats);
double lng = Double.parseDouble(lngs);
LatLng position = new LatLng(lat, lng);
Log.v("###", lats + ", " + lngs + ", " + title);
Log.v("##i=##", String.valueOf(i));
edulList.add(new House(position, title));
i++;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void createMarker() {
mMap.clear();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
MarkerOptions markerOptions = new MarkerOptions();
for (int i = 0; i < edulList.size(); i++) {
LatLng position = edulList.get(i).getLatLng();
String title = edulList.get(i).getTitle();
markerOptions.position(position);
markerOptions.title(title);
mMap.addMarker(markerOptions).hideInfoWindow();
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
});
}
private void createCluster() {
mMap.clear();
mMap.setOnMarkerClickListener(null);
mMap.setInfoWindowAdapter(null);
ClusterManager mClusterManager = new ClusterManager<>(this, mMap);
for (int i = 0; i < edulList.size(); i++) {
LatLng position = edulList.get(i).getLatLng();
String title = edulList.get(i).getTitle();
mClusterManager.addItem(edulList.get(i));
}
mClusterManager.cluster();
mMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener() {
#Override
public boolean onClusterItemClick(final ClusterItem clusterItem) {
infoWindow = getLayoutInflater().inflate(R.layout.markerinfo, null);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
((TextView)infoWindow.findViewById(R.id.tx_infoWindowTitle)).setText(marker.getTitle());
((TextView)infoWindow.findViewById(R.id.tx_infoWindowContent)).setText(marker.getPosition().toString());
return infoWindow;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
});
return false;
}
});
mClusterManager.setOnClusterClickListener(new ClusterManager.OnClusterClickListener() {
#Override
public boolean onClusterClick(Cluster cluster) {
mMap.setInfoWindowAdapter(null);
mMap.moveCamera(CameraUpdateFactory.zoomIn());
return false;
}
});
}
#Override
public void onCameraMove() {
CameraPosition cameraPosition = mMap.getCameraPosition();
float zoom = cameraPosition.zoom;
Log.v("##", "" + pastZoom + " / " + zoom);
if (pastZoom == zoom) {
} else {
if (zoom < 13) {
if(clusters == 0){
createCluster();
marks = 0;
clusters = 1;
}
} else {
if(marks == 0){
createMarker();
marks = 1;
clusters = 0;
}
}
pastZoom = zoom;
}
}
}

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server

I want to show Multiple Markers at runtime on the screen which have different id's that received from the server and longitude and latitude also change or save on server.
** Code work fine in 1 to 1 tracking but not work on multiple Id's PLEASE HELP ME..**
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final LatLng HAMBURG1 = new LatLng(74.3226214, 31.5003567);
static final LatLng HAMBURG = new LatLng(74.3229122, 31.5003193);
private static MainActivity instance;
private static final int ERROR_DIALOG_REQUEST = 9001;
GoogleMap mMap;
int i = 0;
protected static String longitudeServer;
protected static String latitudeServer;
protected static String uniqueidSserver;
protected static String latitudeLast;
protected static String logitudeLast;
protected static String uniqueidlast;
protected static double latilasdoublet;
protected static double longilastdouble;
double latitude = 0;
double longitude = 0;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG, 15);
mLocationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mLocationClient.connect();
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(this, "Map not connected!", Toast.LENGTH_SHORT).show();
}
} else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Add menu handling code
switch (id) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
return super.onOptionsItemSelected(item);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog =
GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null && i == 0) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
return (mMap != null);
}
private void gotoLocation(double lat, double lng, float zoom) {
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, zoom);
mMap.moveCamera(update);
}
public void showCurrentLocation(MenuItem item) {
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mLocationClient);
if (currentLocation == null) {
Toast.makeText(this, "Couldn't connect!", Toast.LENGTH_SHORT).show();
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, 10
);
mMap.animateCamera(update);
}
}
#Override
public void onConnected(Bundle bundle) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
mListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(MainActivity.this, "Location : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_LONG).show();
if (i == 0) {
gotoLocation(location.getLatitude(), location.getLongitude(), 15);
i = 1;
}
AppUtill.UniqueId();
if (AppStatus.getInstance(getContext()).isOnline()) {
new JSONAsyncTask().execute("http://ip/hajjapi/api/GPSLocator/GetLocations");
} else {
Toast.makeText(MainActivity.this, "Turn On your WIFI ", Toast.LENGTH_LONG).show();
}
///HOW I CAN DISPLAY MULTIPLE MARKERS WHICH HAVE DIFFERENT ID'S RECEIVED FROM THE SERVER PLEASE HELP ME PLEASE...
if (marker != null) {
marker.remove();
}
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
}
};
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setInterval(5000);
request.setFastestInterval(5000);
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, mListener);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void showcurrentLocation() {
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
i = 1;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
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);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}
////LAST LONGITUDE AND LATITUDE THAT RECEIVED FROM SERVER
List<String> longitude = Arrays.asList(longitudeServer);
logitudeLast = longitude.get(longitude.size() - 1);
System.out.println(logitudeLast + " logitude ");
List<String> latitude = Arrays.asList(latitudeServer);
latitudeLast = latitude.get(latitude.size() - 1);
System.out.println(latitudeLast + " latitude ");
List<String> uniqueid = Arrays.asList(uniqueidSserver);
uniqueidlast = uniqueid.get(uniqueid.size() - 1);
System.out.println(uniqueidlast + " unique id ");
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
startService(new Intent(getContext(), Services.class));
}
public MainActivity() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
you are using only two double variables for lat and lng. create an arrayList of LatLng objects. for all the urls you get in response, add the LatLng to the arrayList.
add a field
private ArrayList<LatLng> latLngList;
initialize in oncreate function
latLngList = new ArrayList<>();
instead of
latilasdoublet = Double.parseDouble(latitudeLast);
longilastdouble = Double.parseDouble(logitudeLast);
add
for(int i=0; i< latitude.size(); i++){
LatLng latLng = new LatLng(Double.parseDouble(latitude.get(i)), Double.parseDouble(longitude.get(i)));
latLngList.add(latLng);
}
in place of
MarkerOptions options = new MarkerOptions().title("User Name").position(new LatLng(latilasdoublet, longilastdouble)).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
marker = mMap.addMarker(options);
use
ArrayList<MarkerOptions> list = new ArrayList<>();
for (LatLng object : latLngList){
MarkerOptions options = new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4));
mMap.addMarker(options);
list.add(options); //if you want to keep track of all your markers
}
use mMap.clear() to clear all markers and clustering refer
More info on markers.

How to make different routes selectable in google Maps in android?

I'm working on an app which uses lots of google maps interaction. In an activity i've show routes between two point. I want those routes to be selectable, as per the user's choice show please help me.
Here i'm attatching the image of the activity :
And here is the code of the activity shown above :
public class RouteActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
double sl1,sl2,el1,el2;
FrameLayout fl;
TextView distTextView,timeTextView;
String routeArray[];
List<LatLng> list;
List<Polyline> polylineList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
setUpMapIfNeeded();
mMap.getUiSettings().setZoomControlsEnabled(true);
polylineList=new ArrayList<Polyline>();
fl=(FrameLayout)findViewById(R.id.frame_layout);
distTextView=(TextView)findViewById(R.id.distance_textView);
timeTextView=(TextView)findViewById(R.id.time_textView);
String start = getIntent().getStringExtra("start");
String end = getIntent().getStringExtra("end");
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(start, 5);
if (address == null) {
}
Address location = address.get(0);
sl1=location.getLatitude();
sl2=location.getLongitude();
} catch (IOException e) {
e.printStackTrace();
}
try {
address = coder.getFromLocationName(end, 5);
if (address == null) {
}
Address location = address.get(0);
el1=location.getLatitude();
el2=location.getLongitude();
} catch (IOException e) {
e.printStackTrace();
}
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
markers[0]=mMap.addMarker(new MarkerOptions().position(new LatLng(sl1, sl2)).title(start).icon(icon));
markers[1]=mMap.addMarker(new MarkerOptions().position(new LatLng(el1, el2)).title(end).icon(icon));
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
CameraUpdate cu=CameraUpdateFactory.newLatLngBounds(bounds,500,500,0);
mMap.moveCamera(cu);
mMap.animateCamera(cu);
String url=makeURL(sl1,sl2,el1,el2);
Log.e("Generated URL ",url);
new MyAsyncTask().execute(url);
fl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
int x=0;
for (Polyline polyline : polylineList)
{
for (LatLng polyCoords : polyline.getPoints()) {
float[] results = new float[1];
Location.distanceBetween(latLng.latitude, latLng.longitude,
polyCoords.latitude, polyCoords.longitude, results);
if (results[0] < 100) {
mMap.clear();
for(Polyline pl:polylineList)
{
if(pl!=polyline) {
mMap.addPolyline(new PolylineOptions().color(Color.GRAY).addAll(pl.getPoints()));
}
else if(pl==polyline)
{
mMap.addPolyline(new PolylineOptions()
.color(Color.BLUE)
.addAll(pl.getPoints()));
}
}
}
}
}
Log.e("PolyLine ",polylineList.toString());
}
});
}
#Override
protected void onResume() {
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
public class MyAsyncTask extends AsyncTask<String,Void,String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog=new ProgressDialog(RouteActivity.this);
progressDialog.setMessage("Finding Route ...");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... str) {
ParserClass parser = new ParserClass();
String json_str = parser.getJSON(str[0], 2000);
Log.e("JSON Data", json_str);
return json_str;
}
#Override
protected void onPostExecute(String s) {
try {
progressDialog.dismiss();
JSONObject jsonRootObject = new JSONObject(s);
JSONArray routeArray=jsonRootObject.getJSONArray("routes");
Log.e("ROUTES ",routeArray.toString());
for(int i=routeArray.length()-1;i>=0;i--) {
JSONObject routes = routeArray.getJSONObject(i);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
JSONArray legs=routes.getJSONArray("legs");
for(int j=0;j<legs.length();j++)
{
JSONObject distObj=legs.getJSONObject(j);
JSONObject distance =distObj.getJSONObject("distance");
String dist=distance.getString("text");
JSONObject duration=distObj.getJSONObject("duration");
String time=duration.getString("text");
Log.e("Route"+i+" DISTANCE ",dist);
Log.e("Route"+i+" TIME ",time);
distTextView.setText("Distance "+dist);
timeTextView.setText("Time "+time);
}
String encodedString = overviewPolylines.getString("points");
Log.e("Waypoint "+i,encodedString);
list = decodePoly(encodedString);
Log.e("List "+i,list.toString());
if(i==0) {
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.BLUE)
.geodesic(true)
);
Log.e("PolyLine ",line.toString());
polylineList.add(line);
}
else{
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.DKGRAY)
.geodesic(true)
);
polylineList.add(line);
Log.e("PolyLine ",line.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
private void setUpMap() {
mMap.clear();
}
public void showMap(Double l1,Double l2,String str)
{
LatLng position=new LatLng(l1,l2);
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.from);
mMap.addMarker(new MarkerOptions().position(new LatLng(l1, l2)).title(str).icon(icon));
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
CameraUpdate updateZoom=CameraUpdateFactory.zoomTo(15);
googleMap.moveCamera(updatePosition);
googleMap.animateCamera(updateZoom);
}
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("https://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving&alternatives=true&units=imperial");
urlString.append("&key=AIzaSyD5NOOpYKObjlZbt_-4CUOMi14mObzbGNo");
return urlString.toString();
}
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;
}
}
In the abouce code i'm creating these paths using google directions api
Please help in selecting different routes. Thank you
Guys I've achieved the desired functionality, just made some changes in existing code and it's working now. Thanks for your guidance :)

How to add letters in google map markers A-Z using cluster marker

I have a map with 10 waypoints, I'm trying to add letters to specify the path, being "A" the starter point and "J" the ending point. How can I achieve that using clustermarkes, like the image below? this is my code so far:
public class MapaViagem extends FragmentActivity implements ClusterManager.OnClusterClickListener<MyItem>, ClusterManager.OnClusterItemClickListener<MyItem> {
private GoogleMap googleMap;
private String rm_IdViagem;
private List<ClienteModel> mClienteModel = new ArrayList<ClienteModel>();
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
private ArrayList<String> nomes = new ArrayList<String>();
private ViagemModel mViagemModel = new ViagemModel();
private ClusterManager<MyItem> mClusterManager;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
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);
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
String waypoints = "waypoints=optimize:true";
String coordenadas = "";
//if (mClienteModel != null) {
//for (int i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
//mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(rm_IdViagem));
for (int j = 0; j < mEnderecoModel.size(); j++) {
float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
coordenadas += "|" + latitude + "," + longitude;
nomes.add(String.valueOf(j));
coordList.add(new LatLng(latitude, longitude));
startDemo();
addItems(coordList, nomes);
mClusterManager.cluster();
}
String sensor = "sensor=false";
String params = waypoints + coordenadas + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyClusterRenderer extends DefaultClusterRenderer<MyItem> {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(String.valueOf(item.getName()));
}
#Override
protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
}
#Override
protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
return cluster.getSize() > 10;
}
}
public void startDemo() {
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
// mClusterManager.setAlgorithm(new NonHierarchicalDistanceBasedAlgorithm<MyItem>());
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterClickListener(this);
mClusterManager.setOnClusterItemClickListener(this);
}
private class ReadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MapaViagem.this);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Traçando Rotas");
dialog.setCancelable(true);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(4);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
dialog.dismiss();
}
}
#Override
public boolean onClusterClick(Cluster<MyItem> cluster) {
// Show a toast with some info when the cluster is clicked.
String firstName = cluster.getItems().iterator().next().name;
Toast.makeText(this, cluster.getSize() + " (including " + firstName + ")", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onClusterItemClick(MyItem item) {
return false;
}
private void addItems(List<LatLng> markers, List<String> nomes) {
for (int i = 0; i < markers.size(); i++) {
MyItem offsetItem = new MyItem(markers.get(i), nomes.get(i));
mClusterManager.addItem(offsetItem);
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
EDIT:
I'm looking for a solution where I don't need to import a static group of images to my project. I was trying to use the Dynamic icons from google
#Override
protected void onBeforeClusterItemRendered(final MyItem item, final MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
Runnable runnable = new Runnable() {
public void run() {
try {
markerOptions.title(String.valueOf(item.getName()));
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
URL myurl = new URL("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=B%7CFF0000%7CCCCCCC");
Bitmap bmp = BitmapFactory.decodeStream(myurl.openConnection().getInputStream());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bmp));
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
Simple Way is https://code.google.com/p/google-maps-icons/wiki/NumericIcons Follow this link and use icon that, you just need change drawable image what ever when you need
private void addMarkers() {
if (googleMap != null) {
final LatLng WALL_STREET = new LatLng(lat_map, lng_map);
// marker using custom image
googleMap.addMarker(new MarkerOptions()
.position(WALL_STREET)
.title(address_location)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_carmap)));
googleMap
.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String uri = "geo:" + lat_map + "," + lng_map;
startActivity(new Intent(
android.content.Intent.ACTION_VIEW, Uri
.parse(uri)));
}
});
}
}

Categories

Resources