如何在Google Maps v2 for Android中将相机设置为指定位置?

Pan*_*ngu 13 android google-maps

我无法将Google地图相机移回初始位置.基本上,我在Actionbar上有一个主页按钮.如果用户在地图上滚动并点击"主页"按钮,我希望相机移回原始位置.

我使用原始坐标googleMap.getCameraPosition().target,但相机不动.

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    LatLng initialLoc= mMap.getCameraPosition().target;

    CameraUpdate update = CameraUpdateFactory.newLatLng(initialLoc);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);

    mMap.moveCamera(update);
    mMap.animateCamera(zoom);

    return true;
}
Run Code Online (Sandbox Code Playgroud)

map.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context="org.test"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        map:cameraTargetLat="xxx.xxx"
        map:cameraTargetLng="xxx.xxx"
        map:cameraZoom="15"
        map:mapType="normal" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Ant*_*met 38

每当用户选择该选项时,您正在使用

LatLng initialLoc= mMap.getCameraPosition().target;
Run Code Online (Sandbox Code Playgroud)

得到所谓的初始位置,这是错误的! mMap.getCameraPosition().target返回摄像头指向的位置.您应该onCreate()根据您的其他代码将lat长存储在活动或其他位置,然后使用相同的onOptionItemSelected().

顺便说一下,你可以在一个语句中将zoom和lat long结合起来,如下所示.

    LatLng coordinate = new LatLng(lat, lng); //Store these lat lng values somewhere. These should be constant.
    CameraUpdate location = CameraUpdateFactory.newLatLngZoom(
            coordinate, 15);
    mMap.animateCamera(location);
Run Code Online (Sandbox Code Playgroud)

UPDATE

我真的不知道它是多么准确或什么时候打电话给它.但是你可以使用相同的代码

LatLng initialLoc= mMap.getCameraPosition().target;
Run Code Online (Sandbox Code Playgroud)

而是在你的中调用一次onCreate(),或者onResume()然后将它存储在那里.然后下次optionsItemSelected()使用这些值.虽然,为什么不简单地将您在xml中定义的值存储在java代码中然后使用它?