将lat lng传递给Android中的另一个活动

Ban*_*ana 2 android google-maps android-activity

我试图让用户长时间点击地图,而不是创建标记,新活动应该打开.它应包含纬度和经度,即用户点击的位置.

我知道使用对话框时数据传输很容易,但我不想在我的应用程序的这一部分使用对话框片段.

MapActivity:

//Add marker on long click
final double finalLongitude = longitude;
final double finalLatitude = latitude;

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
    // start SendMessageActivity need to add marker to message activity
    Intent intent = new Intent(getActivity(), DisplayLocationActivity.class);
    intent.putExtra("latitude",""+ finalLatitude);
    intent.putExtra("longitude", "" + finalLongitude);
    startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)

DisplayLocationActivity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_set_location);

    Bundle bundle = getIntent().getExtras();
    double lat = bundle.getDouble("latitude");
    double lng = bundle.getDouble("longitude");

    //display lat lng
    mLatDisplay = (TextView) findViewById(R.id.latTextViewDisplay);
    mLangDisplay = (TextView) findViewById(R.id.lngTextViewDisplay);

    mLatDisplay.setText(String.valueOf(lat));
    mLangDisplay.setText(String.valueOf(lng));
}
Run Code Online (Sandbox Code Playgroud)

我的问题是这样的 - 当我启动应用程序并单击地图时,无论我在地图上的哪个位置,新打开的活动都会将lat和lng显示为0.0.

ρяσ*_*я K 8

正如在这里看到经纬度:

public final class LatLng extends Object实现了Parcelable

Means Latlng类实现Parcelable接口,所以我们可以使用Intent.putExtralike 来传递它的direclty :

@Override
public void onMapLongClick(LatLng arg) {
  intent.putExtra("Latlng", arg);
  ..
}
Run Code Online (Sandbox Code Playgroud)

并使用以下内容在下一个Activity中获取它getExtras().getParcelable:

LatLng objLatLng=getIntent().getExtras().getParcelable("Latlng");
Run Code Online (Sandbox Code Playgroud)

现在用于objLatLng在TextView中显示位置坐标.

  • @Kemo:没关系.我刚刚发布了这个答案,以显示在组件之间共享`LatLng`对象的其他简单方法.谢谢 (2认同)