1. Download our Official Android App: Forums for Android!

Apps Android Cluster manager marker icon depending on type

Discussion in 'Android Development' started by Ad621, Apr 10, 2016.

  1. Ad621

    Ad621 Newbie
    Thread Starter
    Rank:
    None
    Points:
    15
    Posts:
    14
    Joined:
    Apr 7, 2016

    Apr 7, 2016
    14
    0
    15
    Male
    Im working on a small app and have implemented Google Maps and Place api. Currently im able to see all my markers on the map and clustering works fine. Im able to zoom in the clusters open up and im able to see the markers. I have a spinner that has different types and once selected that type is passed to the places search string.

    This is the code I have so far

    Code (Text):
    1.  
    2.  
    3. protected void onCreate(Bundle savedInstanceState) {
    4.         super.onCreate(savedInstanceState);
    5.         setContentView(R.layout.activity_maps);
    6.         // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    7.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
    8.                 .findFragmentById(R.id.map);
    9.  
    10.         mMap = mapFragment.getMap();
    11.         onMapReady();
    12.  
    13.         // Array of place types
    14.         placeType = getResources().getStringArray(R.array.placeType);
    15.  
    16.         // Array of place type names
    17.         placeTypeName = getResources().getStringArray(R.array.placeTypeName);
    18.  
    19.         // Creating an array adapter with an array of Place types
    20.         // to populate the spinner
    21.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, placeTypeName);
    22.  
    23.         // Getting reference to the Spinner
    24.         spinPlaceType = (Spinner) findViewById(R.id.spinPlaceType);
    25.  
    26.         // Setting adapter on Spinner to set place types
    27.         spinPlaceType.setAdapter(adapter);
    28.  
    29.         spinPlaceType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    30.             @Override
    31.             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    32.  
    33.                 int selectedPosition = spinPlaceType.getSelectedItemPosition();
    34.                 final String type = placeType[selectedPosition];
    35.  
    36.                 StringBuilder sb = new StringBuilder(
    37.                         "https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    38.                 sb.append("location=" + myLatitude + "," + myLongitude);
    39.                 sb.append("&type=" + type);
    40.                 sb.append("&radius=4000");
    41.                 sb.append("&key=PLACES_KEY");
    42.                 // Creating a new non-ui thread task to download Google place json
    43.                 // data
    44.                 PlacesTask placesTask = new PlacesTask();
    45.  
    46.                 // Invokes the "doInBackground()" method of the class PlaceTask
    47.                 placesTask.execute(sb.toString());
    48.  
    49.             }
    50.  
    51.             @Override
    52.             public void onNothingSelected(AdapterView<?> parent) {
    53.                 StringBuilder sb = new StringBuilder(
    54.                         "https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    55.                 sb.append("location=" + myLatitude + "," + myLongitude);
    56.                 sb.append("&type=restaurant");
    57.                 sb.append("&radius=4000");
    58.                 sb.append("&key=PLACES_KEY");
    59.                 // Creating a new non-ui thread task to download Google place json
    60.                 // data
    61.                 PlacesTask placesTask = new PlacesTask();
    62.  
    63.                 // Invokes the "doInBackground()" method of the class PlaceTask
    64.                 placesTask.execute(sb.toString());
    65.             }
    66.         });
    67.  
    68.  
    69.         // Will display next 20 places returned form the next_page_token
    70.         FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_more);
    71.         fab.setOnClickListener(new View.OnClickListener() {
    72.             @Override
    73.             public void onClick(View view) {
    74.                 Snackbar.make(view, "Finding you some more places.", Snackbar.LENGTH_LONG)
    75.                         .setAction("Action", null).show();
    76.  
    77.                 StringBuilder sb = new StringBuilder(
    78.                         "https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    79.                 sb.append("pagetoken=" + placeJsonParser.getNext_Page_token());
    80.                 sb.append("&key=PLACES_KEY");
    81.                 // Creating a new non-ui thread task to download Google place json
    82.                 // data
    83.  
    84.                 if (placeJsonParser.getNext_Page_token() == "No value for next_page_token"){
    85.                     Snackbar.make(view, "No more places left to find.", Snackbar.LENGTH_SHORT)
    86.                             .setAction("Action", null).show();
    87.                 }
    88.  
    89.                 PlacesTask placesTask = new PlacesTask();
    90.  
    91.                 // Invokes the "doInBackground()" method of the class PlaceTask
    92.                 placesTask.execute(sb.toString());
    93.             }
    94.         });
    95.  
    96.         mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
    97.             @Override
    98.             public void onInfoWindowClick(Marker marker) {
    99.                 Intent detailsIntent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
    100.                 String reference = mMarker.get(marker.getId());
    101.                 marker.getPosition();
    102.                 detailsIntent.putExtra("reference", reference);
    103.                 detailsIntent.putExtra("markerLat", myLatitude);
    104.                 detailsIntent.putExtra("markerLong", myLongitude);
    105.                 startActivity(detailsIntent);
    106.             }
    107.         });
    108.  
    109.     }
    110.  
    111.     public void onMapReady(){
    112.         // Enabling MyLocation in Google Map
    113.         mMap.setMyLocationEnabled(true);
    114.         mMap.getUiSettings().setCompassEnabled(true);
    115.         mMap.getUiSettings().setZoomControlsEnabled(true);
    116.  
    117.         // Getting LocationManager object from System Service
    118.         // LOCATION_SERVICE
    119.         LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    120.  
    121.         // Creating a criteria object to retrieve provider
    122.         Criteria criteria = new Criteria();
    123.  
    124.         // Getting the name of the best provider
    125.         String provider = locationManager.getBestProvider(criteria, true);
    126.  
    127.         // Getting Current Location From GPS
    128.         Location location = locationManager.getLastKnownLocation(provider);
    129.  
    130.         // onLocationChanged(location);
    131.         if (location != null) {
    132.             onLocationChanged(location);
    133.         }
    134.     }
    135.  
    136.     /**
    137.      * A method to download json data from url
    138.      */
    139.     private String downloadUrl(String strUrl) throws IOException {
    140.         String referer ="";
    141.         StringBuilder jsonResults = new StringBuilder();
    142.         HttpURLConnection conn = null;
    143.         try {
    144.             URL url = new URL(strUrl);
    145.  
    146.             // Creating an http connection to communicate with url
    147.             conn = (HttpURLConnection) url.openConnection();
    148.             if (referer != null) {
    149.                 conn.setRequestProperty("Referer", referer);
    150.             }
    151.  
    152.             InputStreamReader in = new InputStreamReader(conn.getInputStream());
    153.  
    154.             // Load the results into a StringBuilder
    155.             int read;
    156.             char[] buff = new char[1024];
    157.             while ((read = in.read(buff)) != -1) {
    158.                 jsonResults.append(buff, 0, read);
    159.             }
    160.             // Displays the list of places found in the terminal.
    161.             Log.i("Data", "Places Found: " + jsonResults);
    162.         } catch (MalformedURLException e) {
    163.             Log.i("Google Places Utility", "Error processing Places API URL");
    164.             return null;
    165.         } catch (IOException e) {
    166.             Log.i("Google Places Utility", "Error connecting to Places API");
    167.             return null;
    168.         } finally {
    169.             if (conn != null) {
    170.                 conn.disconnect();
    171.             }
    172.         }
    173.         return jsonResults.toString();
    174.  
    175.     }
    176.  
    177.  
    178.     /**
    179.      * A class, to download Google Places
    180.      */
    181.     private class PlacesTask extends AsyncTask<String, Integer, String> {
    182.  
    183.         String data = null;
    184.  
    185.         // Invoked by execute() method of this object
    186.         @Override
    187.         protected String doInBackground(String... url) {
    188.             try {
    189.                 data = downloadUrl(url[0]);
    190.             } catch (Exception e) {
    191.                 Log.d("Background Task", e.toString());
    192.             }
    193.             return data;
    194.         }
    195.  
    196.         // Executed after the complete execution of doInBackground() method
    197.         @Override
    198.         protected void onPostExecute(String result) {
    199.             ParserTask parserTask = new ParserTask();
    200.  
    201.             // Start parsing the Google places in JSON format
    202.             // Invokes the "doInBackground()" method of the class ParseTask
    203.             parserTask.execute(result);
    204.         }
    205.  
    206.     }
    207.  
    208.     /**
    209.      * A class to parse the Google Places in JSON format
    210.      */
    211.     private class ParserTask extends
    212.             AsyncTask<String, Integer, List<HashMap<String, String>>> {
    213.  
    214.         JSONObject jObject;
    215.  
    216.         // Invoked by execute() method of this object
    217.         @Override
    218.         protected List<HashMap<String, String>> doInBackground(
    219.                 String... jsonData) {
    220.  
    221.             List<HashMap<String, String>> places = null;
    222.  
    223.             try {
    224.                 jObject = new JSONObject(jsonData[0]);
    225.  
    226.                 /** Getting the parsed data as a List construct */
    227.                 places = placeJsonParser.parse(jObject);
    228.  
    229.             } catch (Exception e) {
    230.                 Log.d("Exception", e.toString());
    231.             }
    232.             return places;
    233.         }
    234.  
    235.         // Executed after the complete execution of doInBackground() method
    236.         @Override
    237.         protected void onPostExecute(List<HashMap<String, String>> list) {
    238.  
    239.             // Clears all the existing markers
    240.             mMap.clear();
    241.             setUpClusterer(list);
    242.  
    243.         }
    244.     }
    245.  
    246.     private void setUpClusterer(List<HashMap<String, String>> list) {
    247.  
    248.         HashMap<String, String> hmPlace;
    249.  
    250.         hmPlace = list.get(0);
    251.  
    252.         // Getting latitude of the place
    253.         double lat = Double.parseDouble(hmPlace.get("lat"));
    254.  
    255.         // Getting longitude of the place
    256.         double lng = Double.parseDouble(hmPlace.get("lng"));
    257.  
    258.         // Position the map.
    259.         mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat,
    260.                 lng), 13));
    261.  
    262.         // Initialize the manager with the context and the map.
    263.         // (Activity extends context, so we can pass 'this' in the constructor.)
    264.         mClusterManager = new ClusterManager<MyItem>(this, mMap);
    265.  
    266.         // Point the map's listeners at the listeners implemented by the cluster
    267.         // manager.
    268.         mMap.setOnCameraChangeListener(mClusterManager);
    269.         mMap.setOnMarkerClickListener(mClusterManager);
    270.  
    271.         mMap.setInfoWindowAdapter(mClusterManager.getMarkerManager());
    272.  
    273.         mMap.setOnInfoWindowClickListener(mClusterManager);
    274.         mClusterManager.setOnClusterItemInfoWindowClickListener(this);
    275.  
    276.         mClusterManager
    277.                 .setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<MyItem>() {
    278.                     @Override
    279.                     public boolean onClusterItemClick(MyItem item) {
    280.                         clickedClusterItem = item;
    281.                         return false;
    282.                     }
    283.                 });
    284.         // Add cluster items (markers) to the cluster manager.
    285.         addItems(list);
    286.  
    287.         mClusterManager.getMarkerCollection().setOnInfoWindowAdapter(
    288.                 new MyCustomAdapterForItems());
    289.     }
    290.  
    291.     public class MyCustomAdapterForItems implements GoogleMap.InfoWindowAdapter {
    292.  
    293.         private final View myContentsView;
    294.  
    295.         MyCustomAdapterForItems() {
    296.             myContentsView = getLayoutInflater().inflate(
    297.                     R.layout.info_window, null);
    298.         }
    299.         @Override
    300.         public View getInfoWindow(Marker marker) {
    301.  
    302.             TextView tvTitle = ((TextView) myContentsView
    303.                     .findViewById(R.id.txtTitle));
    304.             TextView tvSnippet = ((TextView) myContentsView
    305.                     .findViewById(R.id.txtSnippet));
    306.  
    307.             tvTitle.setText(clickedClusterItem.getTitle());
    308.             tvSnippet.setText(clickedClusterItem.getSnippet());
    309.  
    310.             return myContentsView;
    311.         }
    312.  
    313.         @Override
    314.         public View getInfoContents(Marker marker) {
    315.             return null;
    316.         }
    317.     }
    318.  
    319.     private void addItems(List<HashMap<String, String>> list) {
    320.         double latitude;
    321.         double longitude;
    322.  
    323.         for (int i = 0; i < list.size(); i++) {
    324.             HashMap<String, String> hmPlace = list.get(i);
    325.  
    326.             // Getting latitude of the place
    327.             latitude = Double.parseDouble(hmPlace.get("lat"));
    328.  
    329.             // Getting longitude of the place
    330.             longitude = Double.parseDouble(hmPlace.get("lng"));
    331.  
    332.             String name = hmPlace.get("place_name");
    333.  
    334.             // Getting vicinity
    335.             String vicinity = hmPlace.get("vicinity");
    336.             MyItem offsetItem = new MyItem(latitude, longitude, hmPlace.get("reference"), name, vicinity);
    337.             mClusterManager.addItem(offsetItem);
    338.  
    339.         }
    340.     }
    341.  
    342.     public void onClusterItemInfoWindowClick(MyItem item) {
    343.         Intent placesIntent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
    344.         String reference = item.getReference();
    345.         LatLng dest = item.getPosition();
    346.  
    347.         placesIntent.putExtra("name", item.getTitle());
    348.         placesIntent.putExtra("reference", reference);
    349.         placesIntent.putExtra("sourcelat", myLatitude);
    350.         placesIntent.putExtra("sourcelng", myLongitude);
    351.         startActivity(placesIntent);
    352.     }
    353.  
    354.         @Override
    355.     public void onLocationChanged(Location location) {
    356.         myLatitude = location.getLatitude();
    357.         myLongitude = location.getLongitude();
    358.         LatLng myLocation = new LatLng(myLatitude, myLongitude);
    359.         mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
    360.         mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
    361.  
    362.     }
    363.  
    364.     @Override
    365.     public void onStatusChanged(String provider, int status, Bundle extras) {
    366.  
    367.     }
    368.  
    369.     @Override
    370.     public void onProviderEnabled(String provider) {
    371.  
    372.     }
    373.  
    374.     @Override
    375.     public void onProviderDisabled(String provider) {
    376.  
    377.     }
    378. }
    379.  
    380.  
    Currently im able to see just the red markers but i was wondering if theres a way to have a different markers depending on the type selected from the spinner, For example if i select Hospital then the markers are shown as little hospital icons, if i select ATM, then a little ATM icon appears.

    Any help will be appreciated
     

    Advertisement

Share This Page

Loading...