Я хочу попытаться сделать что-то вроде приложения ParkYourCar ... Когда я нажму кнопку «Я», мое местоположение должно быть сохранено, при нажатии кнопки «google maps layout» начнется загрузка и загрузка моих коордов, когда это будет сделано должен сделать маркер там. Можно ли сохранить коорды в текстовом файле, в первом макете и загрузить его из второго макета, который является картами Google? и если это возможно ... Как я могу это сделать?Android Google Maps save Местоположение
Пробовал с InputStreamReader и так далее ... но чем мое приложение chrashed:/
ТНХ для чтения и ответа :)
я получил класс для первого макета, где вы можете нажать кнопку :
public class ParkMyCarActivity extends ActionBarActivity implements View.OnClickListener{
private Button ParkMyCarButton;
private Button LoadMyCarButton;
String koordsFileLat = "koordsLat.txt";
String koordsFileLong = "koordsLong.txt";
String koordsLat;
String koordsLong;
private GoogleMap mMap;
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_park_my_car);
LoadMyCarButton = (Button)findViewById(R.id.button_LoadMyCar);
ParkMyCarButton = (Button)findViewById(R.id.button_ParkMyCar);
ParkMyCarButton.setOnClickListener(new View.OnClickListener() {
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
@Override
public void onClick(View ParkMyCar) {
startActivity(new Intent(ParkMyCarActivity.this, MapsActivity.class));
Location myLocation = locationManager.getLastKnownLocation(provider);
double Latitude = myLocation.getLatitude();
double Longitude = myLocation.getLongitude();
koordsLat = String.valueOf(Latitude);
koordsLong = String.valueOf(Longitude);
}
});
И Google Maps расположение:
public class MapsActivity extends FragmentActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
double latitude2 = 51.844188;
double longitude2 = 8.301594;
public static final String TAG = MapsActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
private LocationRequest myLocationRequest;
static final LatLng florakoords = new LatLng(51.844188,8.301594);
String savedKoordsLat;
String savedKoordsLong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// Macht andere GooglePlayServices einfacher zu benutzen
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Baut das LocationRequest objekt
myLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in millisekunden
.setFastestInterval(1 * 1000); // 1 second, in millisekunden
}
@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 (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
// Erlaubt google maps meine Location zu nutzen
mMap.setMyLocationEnabled(true);
// Ist dazu da das LocationManager aus getSystemService "importiert" wird wofür LocationManager da ist keine ahnung ...
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider (Braucht man um später seine Location zu bestimmen)
Criteria criteria = new Criteria();
// Get the name of the best provider (Ein string mit dem namen provider wird erschaffen, per LocationManager.getBestProvider wird der Name des providers wiedergegeben, der am besten zu criteria passt ... braucht man auch um seine LETZTE Location herauszufinden)
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location (Der finala part mit dem mann seine Location bekommt)
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type (hiermit setzte ich den Kartentyp)
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location (Bekommtden Breitengrad meiner Position aus myLocation)
double latitude = myLocation.getLatitude();
// Get longtitude of the current location (Bekomme den Längengrad meiner Position aus myLocation)
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location (Latlng speichert die Längengrade und Breitengrade als Koordinaten)
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map (Zeigt die jetzige Location in einer "animation")
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map (Zoomt zu unserer Position, Erschafft danach einen Marker an unserer Position mit der Nachricht "Du bist hier")
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
// macht nichts ausser Ein Meldungsfenster zu öffnen ...
new AlertDialog.Builder(this).setMessage("Made by Lars Matthäus").setNeutralButton("ok",null).show();
mMap.addMarker(new MarkerOptions().position(florakoords));
}
// ------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------------------------------
// Ist dazuda, um meine position zu ubdaten
private void handleNewLocation(Location location) {
Marker flora = mMap.addMarker(new MarkerOptions()
.position(florakoords)
.title("Castle")
.alpha(0.7f));
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.addMarker(new MarkerOptions().position(latLng)).setSnippet("Ich bin hier");
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
double entfernung = vergleicheDistanz(currentLatitude,currentLongitude, latitude2,longitude2);
//Rundet Entfernung
entfernung = Math.round(100.0 * entfernung)/100.0;
String entfernungString = String.valueOf(entfernung);
flora.setSnippet(entfernungString);
flora.showInfoWindow();
if (entfernung <= 200.0){
new AlertDialog.Builder(this).setMessage("Noch 200 Meter bis zum Auto!").setNeutralButton("ok",null).show();
}
else {
new AlertDialog.Builder(this).setMessage("Über 200 meter bis zum Auto").setNeutralButton("ok",null).show();
}
}
// ------ -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- ----------------------------------
public static float vergleicheDistanz(double latitude, double longitude, double latitude2, double longitude2) {
Location locationA = new Location("point A");
locationA.setLatitude(latitude);
locationA.setLongitude(longitude);
Location locationB = new Location("point B");
locationB.setLatitude(latitude2);
locationB.setLongitude(longitude2);
float distanz = locationA.distanceTo(locationB);
return distanz;
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
@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 onConnected(Bundle bundle) {
Log.i(TAG, "Location Service Erfolgreich");
//Fragt die letzte Location ab
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient ,myLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
else {
handleNewLocation(location);}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location Service gestoppt. Bitte neu starten");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Попробуйте использовать SharedPreferences для сохранения местоположения. – EliaszKubala
@EliaszKubala Хм, я мог бы попробовать, но сохранит ли он и мою позицию, когда я закрою приложение и снова откроюсь? – genar
@genar Да, это будет локальное хранилище данных, на которое не будут влиять перезагрузки. – dominik4142