我已經實現了一個自定義地圖,允許用戶使用長按來將標記添加到共享首選項,最後我得到了它的工作。在我的地圖上,我有一個按鈕,當按下按鈕時調用方法「清除標記」,我需要退出地圖並重新打開地圖以進行更改。我希望地圖能夠立即更新,並且還有辦法刪除添加到共享偏好設置中的最後一個項目嗎? IE清除前一個標記,不是每一個添加的標記。用於存儲一個標記的代碼是使用共享首選項一次刪除一個標記
@Override
public void onMapLongClick(LatLng latLng) {
addressEditText = (EditText) findViewById(R.id.editTextAddMarker);
title12 = addressEditText.getText().toString();
if (title12.length() > 2) {
MarkerOptions markerOpt1 = new MarkerOptions()
.title(title12)
.anchor(0.5f, 0.5f);
markerOpt1.position(latLng);
mMap.addMarker(markerOpt1);
Toast.makeText(this, "Marker Added", Toast.LENGTH_LONG).show();
locationCount++;
/** Opening the editor object to write data to sharedPreferences */
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString("lat" + Integer.toString((locationCount - 1)), Double.toString(latLng.latitude));
// Storing the longitude for the i-th location
editor.putString("lng" + Integer.toString((locationCount - 1)), Double.toString(latLng.longitude));
//editor.putString("title", addressEditText.getText().toString());
editor.putString("title" + (locationCount-1), addressEditText.getText().toString());
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Saving the values stored in the shared preferences */
editor.commit();
} else if (title12.length() < 1) {
Toast.makeText(this, "Enter title at the top left.", Toast.LENGTH_LONG).show();
}
}
我然後從共享偏好檢索數據,在我onMapReady()
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// If locations are already saved
if (locationCount != 0) {
String lat = "";
String lng = "";
String title13 = "";
// Iterating through all the locations stored
for (int i = 0; i < locationCount; i++) {
// Getting the latitude of the i-th location
lat = sharedPreferences.getString("lat" + i, "0");
// Getting the longitude of the i-th location
lng = sharedPreferences.getString("lng" + i, "0");
SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(this);
title13 = sharedPreferences.getString("title" + i, "0");
//Toast.makeText(this, lat + "," + lng, Toast.LENGTH_LONG).show();
double lat3 = Double.valueOf(lat).doubleValue();
double lng3 = Double.valueOf(lng).doubleValue();
position1 = new LatLng(lat3, lng3);
drawMarker(position1,title13);
}
}
繪製到地圖上最後用於去除標記代碼(問題在這裏)只有當用戶按下按鈕離開並返回到地圖時,按鈕按下後,標記纔會從地圖中移除。它也清除共享首選項,有誰知道我可以刪除最後添加的項目?
private void clearMarker() {
// Opening the editor object to delete data from sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
}
}
以上是通過一個按鈕調用 「的onClick」。有誰知道如何做到這一點?所有的幫助將不勝感激。
你能解釋我到底需要更改還是添加?或者我需要遵循的步驟來實現這一目標?我仍然在開發編程/ android技能,還有很長的路要走。任何提示在正確的方向將不勝感激。 – MichaelCS
我已編輯答案以包含更多詳細信息。希望能幫助到你 :) –