从 google 地图意图获取经纬度

Get lat-lng from google map intent

我是android世界的新人。正在尝试从 google 地图获取当前坐标。我做了一个示例应用程序,它打开 google 地图作为意图(来自 android 网站)。我想要做的是从该意图中获取经纬度。到目前为止我已经做了-

   public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
       // mMap = googleMap;
        Uri uri = Uri.parse("geo:latitude,longitude?z=17");
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}

更新: 我知道我可以在 android 中获取当前坐标。 但我想从 google 地图意图(当前显示标记位置)获得坐标?

请参阅GoogleMap class documentation

public final Location getMyLocation ()
...

Returns the currently displayed user location, or null if there is no location data available.

Returns

  • The currently displayed user location.

Throws

  • IllegalStateException if the my-location layer is not enabled.

然后它又说:

This method is deprecated. use com.google.android.gms.location.FusedLocationProviderApi instead.

因此,如果您确实需要,可以使用 getMyLocation(),但不推荐这样做。它可能 return 为空。或者抛出异常。

代码将类似于:

    @Override
    public void onMapReady(GoogleMap googleMap) {
        // mMap = googleMap;
        Location myLocation;             

        try {
            myLocation = googleMap.getMyLocation();
        }
        catch (IllegalStateException e) {
            // Handle the exception.
        }

        if (!myLocation == null) {
            // Do something with the location if it's not null...
        }
        else {
            // Handle the null location.
        }

        Uri uri = Uri.parse("geo:latitude,longitude?z=17");
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }