如何在android中使用开放街道地图包含GeoJson?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在android中使用开放街道地图包含GeoJson?相关的知识,希望对你有一定的参考价值。
我正在使用Open Street Map,我需要将我添加的点保存在GeoJson中,以便我可以根据保存的坐标,时间和在该类型文件的分析器中打开来显示这些点。
在第一时间,我没有太多数据。我只使用Open Street Map编写代码,但仍需要进行一些更改。
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.BitmapFactory;
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.os.Build;
import android.os.Bundle;
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.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.cocoahero.android.geojson.GeoJSON;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.location.NominatimPOIProvider;
import org.osmdroid.bonuspack.location.POI;
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.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.MinimapOverlay;
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.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import static android.os.Build.VERSION_CODES.M;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements MapEventsReceiver, LocationListener {
private static final int PERMISSAO_REQUERIDA =1 ;
private MapView osm;
private MapController mc;
private CompassOverlay mCompassOverlay;
private MyLocationNewOverlay mLocationOverlay;
private LocationManager locationManager;
private PathOverlay po;
private KmlDocument kmlDocument;
ArrayList<OverlayItem> overlayItemArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
setContentView(R.layout.activity_main);
//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, PERMISSAO_REQUERIDA);
}
}
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
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);
/* locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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
return;
}
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();
// kmlDocument.parseGeoJSON(geoJsonString);
/*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);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSAO_REQUERIDA: {
// Se a solicitação de permissão foi cancelada o array vem vazio.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissão cedida, recria a activity para carregar o mapa, só será executado uma vez
this.recreate();
}
}
}
}
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(R.drawable.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(R.drawable.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();
}
});
}
}
}
我试图实现geojson的结果并不令人满意。我看了几个教程,但没有解释我是否必须实现public void
方法,如果我必须将它放在onCreate
方法中,或者我必须创建一个Java文件。
我怎样才能做到这一点?
答案
您应该在OSMBonusPack GeoJSON features找到您需要的大部分内容。但这是假设您拥有关于Java和Android开发的正确技能水平。
以上是关于如何在android中使用开放街道地图包含GeoJson?的主要内容,如果未能解决你的问题,请参考以下文章
ArcGIS API for JavaScript3.x 学习笔记[4] 加载底图Open Street Map开放街道地图