0

I am not experienced in working with OpenStreetMap, but I am wanting to collect points. All points that the user collects will be saved inside a GeoJSON file, however whenever I use this, the file is replaced, and it ends up taking last point, it is not adding the points within the same file.

I need to do something that increments these points until the user presses the button "Collect data" it saves for example the 10 markings made inside a file that can be GeoJSON, text or KML.

What should I do?

package br.com.josileudorodrigues.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DialogTitle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cocoahero.android.geojson.MultiPoint;

import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.kml.KmlPlacemark;
import org.osmdroid.bonuspack.kml.Style;
import org.osmdroid.bonuspack.routing.GoogleRoadManager;
import org.osmdroid.bonuspack.routing.OSRMRoadManager;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.BoundingBox;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.FolderOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import org.osmdroid.views.overlay.Polyline;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;

import me.drakeet.materialdialog.MaterialDialog;

import static android.os.Build.VERSION_CODES.M;
import static br.com.josileudorodrigues.myapplication.R.drawable.*;

public class MainActivity extends AppCompatActivity implements MapEventsReceiver, LocationListener {

    private static final int REQUEST_PERMISSIONS_CODE = 1;

    private MapView osm;
    private MapController mc;
    private CompassOverlay mCompassOverlay;
    private MyLocationNewOverlay mLocationOverlay;
    private LocationManager locationManager;
    private PathOverlay po;
    private KmlDocument kmlDocument;
    EditText ocorrencia;
    private MaterialDialog mMaterialDialog;
    private static final String FILE_NAME = "example.txt";



    ArrayList<OverlayItem> overlayItemArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //onde mostra a imagem do mapa
        Context ctx = getApplicationContext();
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));


        //Essa é para poder utilizar as permissões
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        osm = (MapView) findViewById(R.id.mapaId);
        ocorrencia = (EditText) findViewById(R.id.ocorrencia);
        osm.setTileSource(TileSourceFactory.MAPNIK);
        osm.setUseDataConnection(true);
        osm.setMultiTouchControls(true);
        osm.setClickable(true);
        osm.setBuiltInZoomControls(true);


        if (Build.VERSION.SDK_INT >= M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION};
                requestPermissions(permissoes, REQUEST_PERMISSIONS_CODE);
            }
        }

        osm.setMapListener(new MapListener() {
            @Override
            public boolean onScroll(ScrollEvent event) {
                Log.i("Script()", "onScroll ()");
                return true;
            }

            @Override
            public boolean onZoom(ZoomEvent event) {
                Log.i("Script()", "onZoom ()");
                return false;
            }
        });


        mc = (MapController) osm.getController();
        GeoPoint center = new GeoPoint(-5.1251, -38.3640);
        mc.setZoom(14);
        mc.animateTo(center);
        addMarker(center);

        //É UMA FUNÇÃO GPS, PORÉM ADICIONA MARCADORES
        // locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this, this);
        osm.getOverlays().add(0, mapEventsOverlay);

        // Aqui adiciona a escala do mapa
        ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(osm);
        osm.getOverlays().add(scaleBarOverlay);

      /*  RoadManager roadManager = new OSRMRoadManager(this);
        ArrayList<GeoPoint> roadpoints = new ArrayList<GeoPoint>();
        roadpoints.add(center);
        GeoPoint endpoints = new GeoPoint(-5.10261,-38.36304);
        roadpoints.add(endpoints);
        Road road = roadManager.getRoad(roadpoints);
        Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
        osm.getOverlays().add(roadOverlay);
        osm.invalidate();*/


        // Aqui salva em GeoJson
      /*  kmlDocument = new KmlDocument();
        kmlDocument.mKmlRoot.addOverlay(roadOverlay,kmlDocument);
        File file = kmlDocument.getDefaultPathForAndroid("mapas.geojson");
        kmlDocument.saveAsGeoJSON(file);*/




        // Aqui salva em KML
    /*    kmlDocument.mKmlRoot.addOverlay(roadOverlay, kmlDocument);
        File localFile1 = kmlDocument.getDefaultPathForAndroid("Mapas.kml");
        kmlDocument.saveAsKML(localFile1);*/


        FolderOverlay folderOverlay = (FolderOverlay) kmlDocument.mKmlRoot.buildOverlay(osm, null, null, kmlDocument);
        osm.getOverlays().add(folderOverlay);
        osm.invalidate();

        this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(ctx), osm);
        this.mLocationOverlay.enableMyLocation();
        osm.getOverlays().add(this.mLocationOverlay);

        this.mCompassOverlay = new CompassOverlay(this, osm);
        this.mCompassOverlay.enableCompass();
        //osm.getOverlays().add(this.mCompassOverlay);
       // osm.getOverlays().add(new RotationGestureOverlay(osm));


    }


    public void addMarker(final GeoPoint center) {
        final Marker marker = new Marker(osm);
        marker.setPosition(center);
        marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
        marker.setIcon(getResources().getDrawable(ic_mapa));
        marker.setDraggable(true);

        marker.setTitle("Jesus");
        marker.setSnippet(center.getLatitude() + "," + center.getLongitude());
        marker.setSubDescription("subDescription Marker");

        marker.setInfoWindow(new CustomMarkerInfoWindow(osm));
        marker.setInfoWindowAnchor(marker.ANCHOR_CENTER, marker.ANCHOR_TOP);

        marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker m, MapView mapView) {
                Log.i("Script", "onMarkerClick");
                m.showInfoWindow();
                InfoWindow.getOpenedInfoWindowsOn(osm);
                return true;
            }
        });

        marker.setOnMarkerDragListener(new Marker.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                Log.i("Script", "onMarkerDragStart()");
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                Log.i("Script", "onMarkerDragEnd()");

            }

            @Override
            public void onMarkerDrag(Marker marker) {
                Log.i("Script", "onMarkerDrag()");
            }
        });


        //osm.getOverlays().clear();
        osm.getOverlays().add(new MapOverlay(this));
        osm.getOverlays().add(marker);
        osm.invalidate();

        kmlDocument = new KmlDocument();
        kmlDocument.mKmlRoot.addOverlay(marker,kmlDocument);
        File file = kmlDocument.getDefaultPathForAndroid("mapas.geojson");
        kmlDocument.saveAsGeoJSON(file);


    }



    public void onResume() {
        super.onResume();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
        osm.onResume(); //needed for compass, my location overlays, v6.0.0 and up
    }

    public void onPause() {
        super.onPause();
        //this will refresh the osmdroid configuration on resuming.
        //if you make changes to the configuration, use
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Configuration.getInstance().save(this, prefs);
        osm.onPause();  //needed for compass, my location overlays, v6.0.0 and up
    }


    @Override
    public void onLocationChanged(Location location) {
        GeoPoint center = new GeoPoint(location.getLatitude(), location.getLongitude());
        mc.animateTo(center);
        addMarker(center);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
            locationManager.removeUpdates((LocationListener) this);
        }
    }

    class MapOverlay extends Overlay {
        public MapOverlay(Context ctx) {
            super(ctx);
        }

        @Override
        public void draw(Canvas c, MapView osmv, boolean shadow) {

        }

        // aqui é onde movimenta o cursor do mapa
        @Override
        public boolean onSingleTapConfirmed(MotionEvent me, MapView mv) {
            Projection p = osm.getProjection();
            GeoPoint gp = (GeoPoint) p.fromPixels((int) me.getX(), (int) me.getY());
            addMarker(gp);
            return (true); // se false ---> vai travar o mapa
        }
    }

    // Aqui quando eu pressionar em uma determinada parte do mapa ele
    // irá  mostrar as minhas cordenadas
    @Override
    public boolean singleTapConfirmedHelper(GeoPoint p) {

        Toast.makeText(this, "Coordenadas:\nLatitude: (" + p.getLatitude() + "\nLongitude: " +
                "" + p.getLongitude() + ")", Toast.LENGTH_SHORT).show();

        // InfoWindow.closeAllInfoWindowsOn(osm); //Clicando em qualquer canto da tela, fecha o infowindow
        return (true);
    }

    //Aqui eu adiciono uma marcação se eu pressionar a tela
    @Override
    public boolean longPressHelper(GeoPoint p) {
        // addMarker(p);
        return true;
    }

    // InfoWindow
    public class CustomMarkerInfoWindow extends MarkerInfoWindow {

        public CustomMarkerInfoWindow(MapView mapView) {
            super(R.layout.bonuspack_bubble, mapView);
        }

        @Override
        public void onOpen(Object item) {

            final Marker m = (Marker) item;

            ImageView iv = (ImageView) mView.findViewById(R.id.bubble_image);
            iv.setImageResource(btn_moreinfo);

            TextView snippet = (TextView) mView.findViewById(R.id.bubble_title);
            snippet.setText(m.getTitle());

            final TextView coordenada = (TextView) mView.findViewById(R.id.coordenadas);
            coordenada.setText(m.getSnippet());

            Button bt = (Button) mView.findViewById(R.id.bubble_buttom);
            bt.setVisibility(View.VISIBLE);
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "Salvo", Toast.LENGTH_SHORT).show();
                    EditText et = (EditText) mView.findViewById(R.id.ocorrencia);

                    kmlDocument = new KmlDocument();
                    kmlDocument.mKmlRoot.addOverlay(m,kmlDocument);
                    File file = kmlDocument.getDefaultPathForAndroid("mapas1.geojson");
                    kmlDocument.saveAsGeoJSON(file);


                }
            });
        }
    }
    public static class MyJSON {

        static String fileName = "myBlog.json";

        public static void saveData(Context context, String mJsonResponse) {
            try {
                FileWriter file = new FileWriter(context.getFilesDir().getPath() + "/" + fileName);
                file.write(mJsonResponse);
                file.flush();
                file.close();
            } catch (IOException e) {
                Log.e("TAG", "Error in Writing: " + e.getLocalizedMessage());
            }
        }

        public static String getData(Context context) {
            try {
                File f = new File(context.getFilesDir().getPath() + "/" + fileName);
                //check whether file exists
                FileInputStream is = new FileInputStream(f);
                int size = is.available();
                byte[] buffer = new byte[size];
                is.read(buffer);
                is.close();
                return new String(buffer);
            } catch (IOException e) {
                Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
                return null;
            }
        }

    }

    // Permissão para geolocalização
    public void callAcessLocation(View view) {
        Log.i("Script", "Acesso a localização()");

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                callDialog("É preciso a permission ACCESS_FINE_LOCATION para apresentação dos eventos locais.", new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS_CODE);
            }

        } else {
            readMyCurrentCoordinates();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.i("Script", "test");
        switch (requestCode) {
            case REQUEST_PERMISSIONS_CODE:
                for (int i = 0; i < permissions.length; i++) {

                    if (permissions[i].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
                            && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        readMyCurrentCoordinates();
                    } /* else if (permissions[i].equalsIgnoreCase(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            && grantResults[i] == PackageManager.PERMISSION_GRANTED) {

                        createDeleteFolder();
                    } else if (permissions[i].equalsIgnoreCase(Manifest.permission.READ_EXTERNAL_STORAGE)
                            && grantResults[i] == PackageManager.PERMISSION_GRANTED) {

                        readFile(Environment.getExternalStorageDirectory().toString() + "/myFolder");
                    }*/
                }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void readMyCurrentCoordinates() {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Location location = null;
        double latitude = 0;
        double longitude = 0;

        if (!isGPSEnabled && !isNetworkEnabled) {
            Log.i("Script", "No geo resource able to be used.");
        } else {
            if (isNetworkEnabled) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, this);
                Log.d("Script", "Network");
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }

            if (isGPSEnabled) {
                if (location == null) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this);
                    Log.d("Script", "GPS Enabled");
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }
        Log.i("Script", "Lat: " + latitude + " | Long: " + longitude);
    }



    /*public void callWriteOnSDCard(View view) {
        Log.i("script", "callWriteOnSDCard()");

        if( ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ){

            if( ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) ){
                callDialog( "É preciso a permission WRITE_EXTERNAL_STORAGE para apresentação do content.", new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE} );
            }
            else{
                ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS_CODE );
            }
        }
        else{
            createDeleteFolder();
        }

    }

    public void callReadFromSDCard(View view) {
        Log.i("script", "callReadFromSDCard()");

        if( ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED ){

            if( ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.READ_EXTERNAL_STORAGE ) ){
                callDialog( "É preciso a permission READ_EXTERNAL_STORAGE para apresentação do content.", new String[]{Manifest.permission.READ_EXTERNAL_STORAGE} );
            }
            else{
                ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS_CODE );
            }
        }
        else{
            readFile(Environment.getExternalStorageDirectory().toString() + "/myFolder");
        }
    }


    // FILE
    private void createDeleteFolder() {
        String path = Environment.getExternalStorageDirectory().toString() + "/myFolder";
        File file = new File(Environment.getExternalStorageDirectory().toString() + "/myFolder");

        if (file.exists()) {
            new File(Environment.getExternalStorageDirectory().toString() + "/myFolder", "myFile.txt").delete();
            if (file.delete()) {
                Log.i("Script", "Folder DELETED!");
            } else {
                Log.i("Script", "Folder delete action was FAIL, take some permissions!");
            }
        } else {
            if (file.mkdir()) {
                createFile(path);
            Log.i("Script", "Folder CREATED!");
            } else {
                Log.i("Script", "Folder create action was FAIL, take some permissions!");
            }
        }
    }

    private void createFile(String path) {
        File file = new File(path + "/myFile.txt");
        OutputStream outputStream = null;

        try {
            outputStream = new FileOutputStream(file);
            outputStream.write(new String("Just a test").getBytes());

            Log.i("Script", "File CREATED!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void readFile(String path) {
        File file = new File(path, "myFile.txt");
        StringBuilder text = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.i("Script", text.toString());
    }

*/
    private void callDialog(String message, final String[] permissions) {
        mMaterialDialog = new MaterialDialog(this)
                .setTitle("Permission")
                .setMessage(message)
                .setPositiveButton("Ok", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        ActivityCompat.requestPermissions(MainActivity.this, permissions, REQUEST_PERMISSIONS_CODE);
                        mMaterialDialog.dismiss();
                    }
                })
                .setNegativeButton("Cancel", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMaterialDialog.dismiss();
                    }
                });
        mMaterialDialog.show();
    }
}

`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.