我有一个大学的项目,使用开放的街道地图进行点标记,即,单击屏幕以进行点或标记,然后将这些点保存在geojson或Json中。
当我创建一些代码时,我将向您展示。但是我无法保存保存在geojson中。
我的代码:
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.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.kml.Style;
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.ScaleBarOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
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;
private MaterialDialog mMaterialDialog;
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);
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);
//setupGeoJson();
//É 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);
kmlDocument = new KmlDocument();
File file = kmlDocument.getDefaultPathForAndroid("map.geojson");
kmlDocument.saveAsGeoJSON(file);
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, new InternalCompassOrientationProvider(this), osm);
this.mCompassOverlay.enableCompass();
osm.getOverlays().add(this.mCompassOverlay);
}
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("DADOS");
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();
}
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) {
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());
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();
}
});
}
}
public static String getGeoString(Context context) throws IOException {
InputStream is = context.getResources().openRawResource(R.raw.json_template);
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);
}
} finally {
is.close();
}
// The local variable 'jsonString' can be inlined as below
return writer.toString();
}
// 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);
}
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();
}
}
With all of that, I wrote this code, but I could not get what I really wanted was to save the points inside a GeoJsoon or Json file, plus I created a raw file, which is down there with the name json_template, but please help me get this job
{
"type": "Feature",
"id": "NYC",
"geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
"properties": {"name": "New-York City"}
}