0

Я добавляю маркер на карте Google, используя onmapclicklistener и удаляя его таким же образом. Я хочу, чтобы, когда пользователь добавляет маркер, его местоположение и радиус сохраняются в списке (радиус берется из пользователя в фрагменте диалога), а когда пользователь удаляет маркер, его также следует удалить из списка. Какой подход я должен использовать. Мой код общественный класс MainActivity расширяет FragmentActivity реализует View.OnClickListener, MapDropdown.DialogListener {Сохранение местоположений маркеров в списке

public static final String mapLongitude="longitude"; 
public static final String mapLatitude="latitude"; 
FragmentManager fm = getSupportFragmentManager(); 
Button displayareas; 
Switch deleteareas; 
private boolean del = false; 


private GoogleMap newmap; // Might be null if Google Play services APK is not available. 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    displayareas = (Button) findViewById(R.id.display); 
    displayareas.setOnClickListener(this); 
    deleteareas = (Switch) findViewById(R.id.delete); 
    deleteareas.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(CompoundButton buttonView, 
            boolean isChecked) { 

      if (isChecked) { 
       del = true; 
       Toast.makeText(getApplicationContext(), "Deleting enabled", Toast.LENGTH_LONG).show(); 
      } else { 
       del = false; 
       Toast.makeText(getApplicationContext(), "Deleting disabled", Toast.LENGTH_LONG).show(); 
      } 

     } 
    }); 
    Log.d("Map","MapCreated"); 
    setUpMapIfNeeded(); 

} 
@Override 
public void onClick(View v) { 
    if (v.getId() == R.id.display) { 
     Intent intent = new Intent(this, AllAreas.class); 

     startActivity(intent); 
    } 

} 

@Override 
protected void onResume() { 
    super.onResume(); 
    //setUpMapIfNeeded(); 
} 


private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (newmap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
       .getMap(); 
     // Check if we were successful in obtaining the map. 
     if (newmap != null) { 
      setUpMap(); 
      Log.d("MAPS","Map working"); 


     } 
     else Log.d("MAPS","not working"); 

    } 
} 


private void setUpMap() { 

    newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet")); 

    // Enable MyLocation Layer of Google Map 
    newmap.setMyLocationEnabled(true); 

    // Get LocationManager object from System Service LOCATION_SERVICE 
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    // Create a criteria object to retrieve provider 
    Criteria criteria = new Criteria(); 

    // Get the name of the best provider 
    String provider = locationManager.getBestProvider(criteria, true); 

    // Get Current Location 
    Location myLocation = locationManager.getLastKnownLocation(provider); 

    // set map type 
    newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

    // Get latitude of the current location 
    double latitude = myLocation.getLatitude(); 

    // Get longitude of the current location 
    double longitude = myLocation.getLongitude(); 

    // Create a LatLng object for the current location 
    LatLng latLng = new LatLng(latitude, longitude); 

    // Show the current location in Google Map 
    newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

    // Zoom in the Google Map 
    newmap.animateCamera(CameraUpdateFactory.zoomTo(20)); 
    newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location")); 

    Log.d("LATITUDE",String.valueOf(latitude)); 
    Log.d("LONGITUDE",String.valueOf(longitude)); 
    GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() { 

     @Override 
     public boolean onMarkerClick(final Marker marker) { 
      if(del == false){ 

      MapDropdown dFragment = new MapDropdown(); 
      // Show DialogFragment 
      dFragment.show(fm, "Dialog Fragment");} 
      else if(del == true){ 
       marker.remove(); 
      } 
      return true; 


     } 

    }; 

    newmap.setOnMarkerClickListener(listener); 

    newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { 

     @Override 
     public void onMapClick(LatLng latLng) { 

      // Creating a marker 
      MarkerOptions markerOptions = new MarkerOptions(); 

      // Setting the position for the marker 
      markerOptions.position(latLng); 

      // Setting the title for the marker. 
      // This will be displayed on taping the marker 
      markerOptions.title(latLng.latitude + " : " + latLng.longitude); 


      // Animating to the touched position 
      newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 

      // Placing a marker on the touched position 
      Marker mmarker = newmap.addMarker(markerOptions); 
      Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude)); 
      Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude)); 

      Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show(); 





     } 
    }); 

} 
@Override 
public void onDialogPositiveClick(DialogFragment dialog){ 
    Log.d("Button","positive"); 

} 
@Override 
public void onDialogNegativeClick(DialogFragment dialog){ 
Log.d("Button","negative"); 

    } 
    } 

ответ

0

Если вы хотите получить список, когда ваше приложение возобновлять. Вы можете использовать location file system для хранения списка.

Прежде всего, если вы хотите сохранить как location, так и radius, для этого вы можете создать объект с именем UserLocation.

Во-вторых создайте Arraylist с именем items для этого объекта, когда пользователь создаст маркер, добавьте этот объект в Arraylist. а затем сохраните Arraylist используя следующий метод:

private void writeItems() { 
     File fileDir = getFilesDir(); 
     File locationFile = new File(fileDir, "locations.txt"); 
     try { 
      FileUtils.writeLines(locationFile, items); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

Наконец, вы можете получить данные с помощью этого:

private void readItems() { 
     File filesDir = getFilesDir(); 
     File locationFile = new File(filesDir, "locations.txt"); 
     try { 
      items = new ArrayList<UserLocation>(FileUtils.readLines(locationFile)); 
     } catch (IOException e) { 
      items = new ArrayList<locationFile>(); 
     } 
    }