首先,需要在build.gradle文件中添加Google Play服务库依赖项:
implementation 'com.google.android.gms:play-services-location:17.0.0'
在布局文件中添加一个按钮和一个TextView,用于显示经纬度:
让你的Activity或Fragment实现LocationPickerDialog.OnLocationSelectedListener接口:
public class MyActivity extends AppCompatActivity implements LocationPickerDialog.OnLocationSelectedListener { // ... @Override public void onLocationSelected(double latitude, double longitude) { // Handle location selection here // Update the TextView with latitude and longitude TextView tvLocation = findViewById(R.id.tv_location); tvLocation.setText(String.format("Selected Location: %f, %f", latitude, longitude)); } }
在你的Activity或Fragment中,定义一个按钮点击事件,当用户点击按钮时,弹出位置选择器:
btn_pick_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Show location picker dialog LocationPickerDialog dialog = new LocationPickerDialog(); dialog.show(getSupportFragmentManager(), "locationPicker"); } });
创建一个LocationPickerDialog类,并在其中实现位置选择器的逻辑,并通过回调接口将位置信息传递回Activity或Fragment:
public class LocationPickerDialog extends DialogFragment implements OnMapReadyCallback {
// ...
private OnLocationSelectedListener mListener;
// ...
@Override
public void onMapReady(GoogleMap googleMap) {
// Setup map and markers
// Handle marker click events and update latitude and longitude
// Call mListener.onLocation