【发布时间】:2015-08-08 16:02:51
【问题描述】:
我想尝试制作类似于 ParkYourCar 应用程序的东西...当我单击按钮时,我的位置应该被保存,在按钮上单击谷歌地图布局将开始并加载我的 koords,完成后它应该在那里做一个标记.是否可以在第一个布局中将 koords 保存在文本文件中并将其加载到谷歌地图的第二个布局中?如果可能的话......我该怎么做?
用 Inputstreamreader 等尝试过......但我的应用程序崩溃了:/
感谢阅读和回复:)
我为第一个布局提供了一个类,您可以在其中单击一个按钮:
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);
}
});
还有谷歌地图布局:
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 嗯,我可以试试,但是当我关闭应用程序并再次打开时,它还会保存我的位置吗?
-
@genar 是的,它会的,它的本地数据存储不受重启的影响。
-
k thx :) 你现在能帮我解决另一个问题吗?当地图活动启动时..它会立即崩溃,但前提是我使用 .getLatitude 或 .getlonitude ...这是我的代码
标签: android google-maps save load