2016-09-16 51 views
0

我正在創建一個Android地圖應用程序,我想在當前位置創建標記並顯示以前的這些標記。我可以在當前位置創建標記,但是當我在其他位置恢復應用時,我的應用只顯示當前位置標記,而不是之前的位置標記。請幫忙。這裏是我的嘗試:在Android地圖上保存標記App

public class Main extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener { 

private GoogleMap mMap; 
private GoogleApiClient mGoogleApiClient; 
public Location mLastLocation; 
ArrayList<LatLng> listOfPoints = new ArrayList<>(); 
public boolean isMapReady = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 

    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

    } 
} 


public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    isMapReady = true; 
} 

public boolean onMarkerClick(final Marker marker) { 
    return false; 
} 

public void onConnected(Bundle connectionHint) { 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

     return; 
    } 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

     return; 
    } 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 

    MarkerOptions mp = new MarkerOptions(); 
    mp.position(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())); 

    mp.title("my position"); 

    mMap.addMarker(mp); 

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
      new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()), 16)); 
    LatLng newLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()); 
    listOfPoints.add(newLatLng); 


    } 

public void onConnectionSuspended(int i) { 

} 

public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

protected void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

protected void onStop() { 
    super.onStop(); 
    mGoogleApiClient.disconnect(); 

} 

protected void onPause() { 
    super.onPause(); 
    try { 
     // Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE 
     FileOutputStream output = openFileOutput("latlngpoints.txt", 
       Context.MODE_PRIVATE); 
     DataOutputStream dout = new DataOutputStream(output); 
     dout.writeInt(listOfPoints.size()); // Save line count 
     for (LatLng point : listOfPoints) { 
      dout.writeUTF(point.latitude + "," + point.longitude); 
      Log.v("write", point.latitude + "," + point.longitude); 
     } 
     dout.flush(); // Flush stream ... 
     dout.close(); // ... and close. 
    } catch (IOException exc) { 
     exc.printStackTrace(); 
    } 
} 

protected void onResume(){ 
    super.onResume(); 
    if (isMapReady==true){ 
     try { 
      FileInputStream input = openFileInput("latlngpoints.txt"); 
      DataInputStream din = new DataInputStream(input); 
      int sz = din.readInt(); // Read line count 
      for (int i = 0; i < sz; i++) { 
       String str = din.readUTF(); 
       Log.v("read", str); 
       String[] stringArray = str.split(","); 
       double latitude = Double.parseDouble(stringArray[0]); 
       double longitude = Double.parseDouble(stringArray[1]); 
       listOfPoints.add(new LatLng(latitude, longitude)); 
      } 
      din.close(); 
      loadMarkers(listOfPoints); 
     } catch (IOException exc) { 
      exc.printStackTrace(); 
     } 
    } 
} 
protected void onSaveInstanceState(Bundle outState){ 
    super.onSaveInstanceState(outState); 

    outState.putParcelableArrayList("places", listOfPoints); 
} 
private void restore(Bundle outState){ 
    if (outState != null) { 
     listOfPoints =(ArrayList<LatLng>)outState.getSerializable("places"); 
    } 
} 
protected void onRestoreInstanceState(Bundle outState) { 
    super.onRestoreInstanceState(outState); 
    restore(outState); 
} 
private void loadMarkers(List<LatLng> listOfPoints) { 
    int i=listOfPoints.size(); 
    while(i>0){ 
     i--; 
     double Lat=listOfPoints.get(i).latitude; 
     double Lon=listOfPoints.get(i).longitude; 
     MarkerOptions mp = new MarkerOptions(); 

     mp.position(new LatLng(Lat, Lon)); 

     mp.title("my previous position"); 

     mMap.addMarker(mp); 

     mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
       new LatLng(Lat, Lon), 16)); 
    } 
} 
} 
+0

看起來你是非常接近得到這。 – danny117

+0

檢查這個答案http://stackoverflow.com/questions/33430559/how-to-make-a-search-on-google-maps-for-finding-hospitals-etc/33431118#33431118 – AndroidHacker

+0

通過你的代碼看起來它看起來就像你正在做所有正確的事情來保存和加載標記。有趣的一件事是如果(isMapReady == true) 每當onResume發生時,現在這種情況是不是真的?這可能是因爲onResume發生時,地圖尚未準備好。你能證實這一點嗎? – CrashOverride

回答

1

注意:

onPause()方法您在保存文件包含在listOfPoints的位置,但你永遠不添加最後已知位置到該列表。您可能想要在onConnect()方法中添加。

編輯:當你啓動應用程序,調用onCreate()onStart()onResume()方法(see Activity Lifecycle)。這意味着,當地圖還沒有準備好時,addMarker()方法可能會被調用。只有在之前調用onMapReady()方法時,您可能需要添加標記。

編輯(因爲你更新的代碼):

  • 使用openFileOutput("latlngpoints.txt", Context.MODE_APPEND),而不是Context.MODE_PRIVATE
  • 你應該從文件中讀取的標記也onMapReady()onConnected(Bundle connectionHint)就像你在onResume()方法做(因爲當您運行應用程序時,地圖還沒有準備就緒,您將不會執行任何操作,只能在您的onResume()

還要注意,您的文件將可能containt重複

+0

我修改了我的代碼,在onConnect()方法中包含這些行: LatLng newLatLng = new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()); listOfPoints.add(newLatLng); 但現在當我嘗試運行代碼時,它給了我錯誤「無法恢復活動,因爲嘗試在loadMarkers代碼中調用虛擬方法addMarkers」。 –

+0

你可以請建議的方式來做到這一點? –

+0

@AkhilAgarwal您可以使用'isMapReady'布爾屬性(默認爲'false'),並在'onMapReady()'方法中將其設置爲'true'。那麼只有當'isMapReady'爲'true'時,才應該在'onResume()'方法中更新地圖。看看https://developers.google.com/maps/documentation/android-api/map#add_map_code,如果你還沒有設置onMapReady()回調 – Sith