0

I created an App that uses Google Maps to get the users current location and draw routes. Recently I converted this app to a TabHost with five tabs. Because of this I now need a way to clear and restart the map whenever a user clicks on that tab. How can I do this. Below is the layout.xml and activity code for my map.

activity_map_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/btn_draw"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=" Get Directions"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_find"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_btn_find"
            android:layout_alignParentRight="true" />

        <EditText
            android:id="@+id/et_location"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:hint="@string/hnt_et_location"
            android:layout_toLeftOf="@id/btn_find" />

    </RelativeLayout>



    <fragment 
          android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>

And below is my is my on create method for MapviewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    markerList = new ArrayList<Marker>();



    if (EvacRouteTableActivity.evacRouteStr !=null){
        fuelStopBundle = EvacRouteTableActivity.evacRouteStr;
        evacName = EvacRouteTableActivity.evacRouteStr;

    } else if (FuelStopActivity.type != null){
        fuelStopBundle = FuelStopActivity.type;
        shelorfuelAddress = FuelStopActivity.type;
    } else if (ShelterActivity.type != null){
        fuelStopBundle = ShelterActivity.type;
        shelorfuelAddress = ShelterActivity.type;
    }
    //List<EvacRoute> evacRouteList = new ArrayList<EvacRoute>(DALController.sharedInstance().getAllEvacRoutes());
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<FuelStop> fuelStopList = new ArrayList<FuelStop>();
    List<Shelter> shelterList = new ArrayList<Shelter>();
    final boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    setContentView(R.layout.activity_map_view);
    MapAsyncClass ac = new MapAsyncClass(MapViewActivity.this);
    ac.execute();
    Button btn_find = (Button) findViewById(R.id.btn_find);
    btn_directions = (Button) findViewById(R.id.btn_draw);
    // Getting reference to btn_find of the layout activity_main

    final EditText etLocation = (EditText) findViewById(R.id.et_location);
    if (isGPS){
        btn_find.setVisibility(View.GONE);
        etLocation.setVisibility(View.GONE);
    } else {
        btn_find.setVisibility(View.VISIBLE);

        etLocation.setVisibility(View.VISIBLE);     
        btn_directions.setVisibility(View.GONE);
    }


    //shelorfuelAddress = fuelStopBundle.getString("key");
    /**
     * This will make sure that if the user selects the 
     */

    if (fuelStopBundle != null && evacName != null){



        //showCurrentLocationOnMap();   


        // Defining button click event listener for the find button
        findClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                // Getting user input location
                String location = etLocation.getText().toString();


                if(location!=null && !location.equals("")){
                    currentLocation = getLocationFromAddress(location);

                    AsyncTask<String, Void, List<Address>> execute = new GeocoderTask().execute(location);
                    String latStr = String.valueOf(latitude);
                    String longStr = String.valueOf(longitude);

                    try {
                        evacRoute = DALController.sharedInstance().getEvacuationRoutewithoutgps(evacName, currentLocation, latStr, longStr);
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ParserConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SAXException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    showEvacuationRoute(evacRoute);
                }
            }
        };
  }
  showCurrentLocationOnMap();

  if (isGPS){
  // Defining button click event listener for the find button
      OnClickListener directionsClickListener = new OnClickListener() {
          @Override
          public void onClick(View v) {
              if (shelorfuelAddress!=null){
                  Intent intent = new Intent(android.content.Intent.ACTION_VIEW,    
                          Uri.parse("http://maps.google.com/maps?saddr=<"+latitude+">,<"+longitude+">&daddr=<"+currentFuelLat+">,<"+currentFuellong+">"));
                  startActivity(intent);
              } else {
                  LatLng destLatLng = DALController.sharedInstance().getDestPoint();        
                  Double latDouble = destLatLng.latitude;
                  Double longDouble = destLatLng.longitude;
                  Intent intent = new Intent(android.content.Intent.ACTION_VIEW,        
                          Uri.parse("http://maps.google.com/maps?saddr=<"+latitude+">,<"+longitude+">&daddr=<"+latDouble+">,<"+longDouble+">"));
                  startActivity(intent);                
              }


          }
      };
      btn_directions.setOnClickListener(directionsClickListener);
  }

  btn_find.setOnClickListener(findClickListener);

  /**
   * this ensures that if the user clicked on the Mapview from the MainActivity
   * that ten shelters and ten fueling points will show on the map
   */
  if (shelorfuelAddress==null && isGPS){


      // Setting button click event listener for the find button
      btn_find.setOnClickListener(findClickListener);
      fuelStopList = DALController.sharedInstance().getAllFuelStops();
      shelterList = DALController.sharedInstance().getAllShelters();
      if (fuelStopList == null){

      } else {
          for (FuelStop fuelStop : fuelStopList){


              try {
                  ShowFuelStop(fuelStop.getAddress());
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }

      for (Shelter shelter : shelterList){

          try {
              ShowShelters(shelter.getAddress());
          } catch (IOException e) {
              e.printStackTrace();
          }
      }      

  }

  mMenu = new CustomMenu(this, this, getLayoutInflater());
  mMenu.setHideOnSelect(true);
  mMenu.setItemsPerLineInPortraitOrientation(4);
  mMenu.setItemsPerLineInLandscapeOrientation(8);
  //load the menu items
  loadMenuItems();
}
yams
  • 942
  • 6
  • 27
  • 60

3 Answers3

0

Use mapview.clear() than mapview.invalidate() . After every UI change you should call invalidate() on mapview.

kaushal trivedi
  • 3,405
  • 3
  • 29
  • 47
  • I don't have a mapview on my xml. How do I create this and clear it could you give me a example. All I have in the xml is a mapfragment. – yams Jun 27 '13 at 22:39
  • Well i have never use mapfragment before , but there must be some method to wipe out all the data from it , let me see some stuff on mapfragment and i will reply you. – kaushal trivedi Jun 27 '13 at 22:41
  • Ok My whole layer.xml is posted above. – yams Jun 27 '13 at 22:42
  • Have you come up with something? – yams Jun 28 '13 at 00:32
  • Hey , i got that you can get the Current googleMap instance used by your MapFragment via getMap() method . Use this method on your SupportMapFragment instance and than call the clear method on your maps' instance once you get it. – kaushal trivedi Jun 28 '13 at 17:52
  • Where do you clear them ? You have to find the method that is being called when you switch from one tab to other , and try clearing the things on that method. – kaushal trivedi Jun 28 '13 at 19:52
  • Do your onResume called each time you return to the tab that contains mapFragment ? There is one final option to completely remove the MapFragment and re create it if you dont have any data dependency there .I mean if you dont want its data to use on some other tab. – kaushal trivedi Jun 28 '13 at 20:06
  • It did every time so what is the other option I do not need the data on the map as I would like the data to get cleared each time the user clicks off the map anyways. – yams Jun 28 '13 at 20:11
0

I found with time the the map.clear() was working but objects where getting re added to the map because of the use of some of the global variables that I needed. So I had to do a map.clear() on the onResume() then do some object deallocation. Once I did this it worked, and actually deallocating the objects helped with garbage collection on the map as java has problems collecting items that still have a reference. See Code below.

@Override
public void onResume(){
    super.onResume();
    if (map != null){
        onCreateCalled += 1;
        if (onCreateCalled >=3){
            if (fuelPolyLine != null){
                fuelPolyLine.remove();
                fuelPolyLine = null;
                fuelStoprectLine = null;
            }
            if (shelterPolyLine != null){
                shelterPolyLine.remove();
                shelterPolyLine = null;
                shelterRectLine = null;
            }
            if (evacPolyLine != null){
                evacPolyLine.remove();
                evacPolyLine = null;
                evacRouteRectLine = null;
            }
            map.clear();
            currentLocation = null;
            map = null;
            markerOptions = null;
            evacRoute = null;
            lm = null;
            ll = null;
            mf = null;


            setupMap();

        }


    }
}
yams
  • 942
  • 6
  • 27
  • 60
-2
       setContentView(R.layout.activity_map_view);

     //
       SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
       map = fm.getMap();
       //
H4F
  • 131
  • 10
  • Ok but why get the FragmentManager if you aren't gonna use it – yams Jun 27 '13 at 22:45
  • And also there is no MarkerPoints. – yams Jun 27 '13 at 22:46
  • because in your layout you use fragment not mapview try it without markerpoint>>>> – H4F Jun 27 '13 at 22:47
  • Yeah but MarkerPoints doesn't come up when I type it. – yams Jun 27 '13 at 22:49
  • There is no library class for MarkerPoints – yams Jun 27 '13 at 22:50
  • That just clears the list not the markers. I don't have a mapview in this. I am using the SupportFragmentManager. – yams Jun 27 '13 at 22:52
  • I know so I am and it work but in @Override public void onMapClick – H4F Jun 27 '13 at 23:07
  • Hmmmmm you need to Getting reference to SupportMapFragment of the activity , add this to onCreat : SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); and this: map = fm.getMap(); – H4F Jun 27 '13 at 23:13
  • It does nothing but load the map with the old markers and everything else. – yams Jun 27 '13 at 23:43