我正在使用Android Studio制作应用程序,即使我已经获得了地图并且正在显示,我也无法添加标记或对其执行任何其他操作从OnMapReady获取的GoogleMap对象。
这是我的主要活动中的代码:
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener, OnMapReadyCallback {
MapFragment mapFragment;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchFragments(GlobalConsts.FRAGMENT.MAP);
}
public void switchFragments(GlobalConsts.FRAGMENT fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
switch (fragment) {
case MAP:
if (mapFragment == null) {
mapFragment = new MapFragment();
}
mapFragment.getMapAsync(this);
transaction.replace(R.id.fragmentContainer, mapFragment);
transaction.addToBackStack(null);
break;
}
transaction.commit();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
这是我的主要活动的xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
tools:context="jarett.familymap.MainActivity">
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
我的MapFragment类:
public class MapFragment extends SupportMapFragment {
public MapFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
和fragment_map.xml中我的MapFragment的xml布局:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mapFragment"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
tools:context="jarett.familymap.MapFragment">
</fragment>
就像我说的那样,就显示地图片段而言,一切似乎都运行正常,但对于我的生活,我无法弄清楚为什么缩放和添加标记的代码没有做任何事情。我很感激帮助。