How to show infowindow without cluster click - android

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;
}
}
}

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 separate main route and alternate routes' polyline google map 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!

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 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)));
}
});
}
}

how to display proper muliple data of respective marker into infowindow

here i want to show detail onclick of marker into infowindow according to its latlong and want to do new event onclick infowindow. here i made a markerlist and lat1 long1 array which is taking from url and you can see private void setUpMapIfNeeded() this function
Here nameb is containing marker names list
public class Mainactivity extends FragmentActivity {
String friendid;
Double lng1;
Double lat1;
String lat;
String lon;
String gen;
String test;
String gender;
String result;
Drawable drawable;
String frid;
String nameb;
private GoogleMap mMap;
ImageView logout;
private static final int DIALOG_ALERT = 10;
Bitmap bm;
static boolean Iscamera=false;
ArrayList<Double> arrayLat = null;
ArrayList<Double> arrayLong = null;
ArrayList<String> arrayGender = null;
ArrayList<String> arrayUsername = null;
ArrayList<String> arrayFrnd = null;
static ArrayList<Marker> markerList = null;
EventListTask eventListTask;
TextView tvLng;
TextView tvLat;
private static final int NOTIFICATION_ID = 1;
private AQuery androidAQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flirtalerthome_screen);
logout = (ImageView) findViewById(R.id.logoutimage);
//*************************************************************************************************************
androidAQuery=new AQuery(this);
androidAQuery.ajax(Constant.Profile_Image, Bitmap.class, 0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, com.androidquery.callback.AjaxStatus status) {
super.callback(url, object, status);
bm=object;
//You will get Bitmap from object.
}
});
// ***************************************************************************************************************
new EventListTask().execute();
logout.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_ALERT);
}
});
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
new EventListTask().execute();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mMap.clear();
if(!Iscamera){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()), 20));
Iscamera = true;
}
try{
mMap.setInfoWindowAdapter(new InfoWindowAdapter()
{
// Use default InfoWindow frame
public View getInfoWindow(Marker marker) {
return null;
}
// Defines the contents of the InfoWindow
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting the position from the marker
//
// Getting reference to the TextView to set latitude
tvLat = (TextView) v.findViewById(R.id.tv_lat);
// Getting reference to the TextView to set longitude
// TextView tv = (TextView) v.findViewById(R.id.tv);
// Setting the latitude
// tvLat.setText();
// Setting the longitude
// tvLng.setText(nameb);
// Returning the view containing InfoWindow contents
return v;
}
});
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.getLatitude(), arg0
.getLongitude()))
.title(Constant.USERNAME)
.icon(BitmapDescriptorFactory.fromBitmap(bm)));
}catch (Exception e){
Toast.makeText(getApplicationContext(),
e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(),
e.getMessage(), e);
}
}
});
}
}
}
#SuppressWarnings("unused")
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
"Marker"));
}
// ***********************************************************************************************************************
#SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
// Create out AlterDialog
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure,want to logout");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new OkOnClickListener());
builder.setNegativeButton("No", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(FlirtHome_Screen.this, LoginScreen.class);
SharedPreferences settings = getSharedPreferences(
Constant.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", null);
editor.commit();
startActivity(intent);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
}
// ********************************************************************************************************************
private class EventListTask extends AsyncTask<Context, Void, Void> {
ProgressDialog dialog = new ProgressDialog(FlirtHome_Screen.this);
String message;
String s;
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Loading....please wait ");
dialog.setCancelable(false);
dialog.show();
}
protected Void doInBackground(Context... params) {
try {
message = myMethod();
s = saveData(message);
// bm = drawableToBitmap(draw);
} catch (Exception e) {
System.out.print(e.getMessage());
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (s == null) {
} else {
for (int i = 0; i < arrayLat.size(); i++) {
lat1 = arrayLat.get(i);
lng1 = arrayLong.get(i);
gen = arrayGender.get(i);
frid = arrayFrnd.get(i);
nameb = arrayUsername.get(i);
if (gen.equals("1")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.bluesmilelarge))));
} else if (gen.equals("2")) {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
} else {
markerList
.add(mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title(nameb)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.purplesmilelarge))));
}
}
}
dialog.dismiss();
}
}
public String myMethod() throws IOException, JSONException {
String url1 = "url";
System.out.println("In get Category method" + url1);
URL url = new URL(url1);
URLConnection urlcon = url.openConnection();
String jsonresponse = convertStreamToString(urlcon.getInputStream());
Log.e("response", jsonresponse);
return jsonresponse;
}
public String convertStreamToString(InputStream is) {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return writer.toString();
} else {
return "";
}
}
private String saveData(String result) {
try {
arrayLat = new ArrayList<Double>();
arrayLong = new ArrayList<Double>();
arrayGender = new ArrayList<String>();
arrayUsername = new ArrayList<String>();
arrayFrnd = new ArrayList<String>();
markerList = new ArrayList<Marker>();
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
JSONObject json2 = json.getJSONObject("response");
JSONArray jsonArray = json2.getJSONArray("incircle");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
test = objJson.getString("username");
arrayUsername.add(test);
friendid = objJson.getString("useid");
arrayFrnd.add(friendid);
Constant.FRIENDIDLIST.add(friendid);
lat = objJson.getString("lat");
Constant.LATITUDEFLIST.add(lat);
arrayLat.add(Double.parseDouble(lat));
lon = objJson.getString("log");
Constant.LONGITUDEFLIST.add(lon);
arrayLong.add(Double.parseDouble(lon));
gender = objJson.getString("gender");
arrayGender.add(gender);
}
} catch (JSONException e) {
e.printStackTrace();
}
return test;
}
public void onBackPressed() {
return;
}
}
For showing different items in infowindow you need to use infowindowadapter.
Here is sample code.You can take reference from here.
private GoogleMap googleMap;
private double[][] arrayLatLng = new double[][] { { 21.943046, 72.088989 }, { 26.843677, 73.407349 }, { 30.315988, 77.076782 }, { 29.05617, 82.042603 }, { 25.819672, 85.90979 },
{ 24.726875, 89.667114 }, { 22.87744, 86.766724 }, { 18.937464, 82.723755 }, { 15.411319, 79.603638 }, { 12.618897, 77.670044 }, { 15.771109, 74.747681 }, { 20.055931, 73.780884 } };
private String[] locationName = new String[] { "Bhavnagar, Gujarat", "Rajasthan", "Chandigarth", "Nepal", "Bihar", "Bangladesh", "West Bengal", "Orissa", "Andhra Pradesh", "Karnataka",
"Bail Hongal, Maharastra", "Nasik, Maharastra" };
private MarkerInfoWindowAdapter infoWindowAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setOnMarkerClickListener(this);
googleMap.setOnInfoWindowClickListener(this);
googleMap.getUiSettings().setAllGesturesEnabled(true);
// infoWindowAdapter = new MarkerInfoWindowAdapter();
googleMap.setInfoWindowAdapter(infoWindowAdapter);
final PolygonOptions polygonOptions = new PolygonOptions();
polygonOptions.strokeColor(Color.BLUE);
polygonOptions.strokeWidth(3);
// polygonOptions.fillColor(Color.RED);
for (int i = 0; i < arrayLatLng.length; i++) {
final LatLng latLng = new LatLng(arrayLatLng[i][0], arrayLatLng[i][1]);
polygonOptions.add(latLng);
googleMap.addMarker(new MarkerOptions().position(latLng).title(locationName[i]).snippet(arrayLatLng[i][0] + ", " + arrayLatLng[i][1])
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker)));
infoWindowAdapter = new MarkerInfoWindowAdapter();
infoWindowAdapter.setTitle(locationName[i]);
infoWindowAdapter.setDescription(locationName[i]);
}
googleMap.addPolygon(polygonOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(arrayLatLng[0][0], arrayLatLng[0][1]), 4));
}
#Override
public boolean onMarkerClick(Marker marker) {
Log.e("Marker Click", "Click Found");
// marker.showInfoWindow();
return false;
}
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.isInfoWindowShown()) {
marker.hideInfoWindow();
}
}
class MarkerInfoWindowAdapter implements InfoWindowAdapter {
private View inflatedView;
private View tempView;
private String title, description;
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
MarkerInfoWindowAdapter() {
inflatedView = getLayoutInflater().inflate(R.layout.location_info_window, null);
tempView = getLayoutInflater().inflate(R.layout.location_content_window, null);
}
#Override
public View getInfoContents(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
#Override
public View getInfoWindow(Marker marker) {
setInfo(marker, inflatedView);
return inflatedView;
}
private void setInfo(Marker marker, View view) {
final TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
final TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
txtTitle.setText(title);
txtDescription.setText(description);
}
}

Categories

Resources