简体   繁体   English

无法在片段内使用Google Map V2

[英]Unable to use google map V2 inside fragment

I know this question has already been asked a few times, but I cant find a solution to my problem by looking at them. 我知道这个问题已经被问过几次了,但是通过查看它们我找不到解决方案。 I have created a navigation drawer. 我已经创建了一个导航抽屉。 The navigation drawer naturally helps switching fragments. 导航抽屉自然有助于切换片段。 Inside one such fragment, I want to show up a google map. 在一个这样的片段中,我想显示一个谷歌地图。

The map_fragment.xml : map_fragment.xml

<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

The MapFragment : MapFragment

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;



public class MapFragment extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.map_fragment, container, false);

        GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    return view;


     }


}

The line: 该行:

GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

Always shows: 始终显示:

Cannot cast from Fragment to SupportMapFragment 无法从Fragment投射到SupportMapFragment

I am not sure why is this showing up? 我不确定为什么会出现这种情况? Where am I going wrong? 我要去哪里错了? I have provided all the required permissions in the Manifest as I am able to see google map in other activities. 我已经在清单中提供了所有必需的权限,因为我能够在其他活动中看到google map。

This is best practice to use google map , try it. 这是使用google map的最佳实践,请尝试一下。

public class MapFragment extends Fragment implements OnMapReadyCallback{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.map_fragment, container, false);

   // GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    MapFragment map = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

    map.getMapAsync(this);
return view;


 }

@Override
public void onMapReady(GoogleMap googleMap) {
    //googleMap is your map

    googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    gm = googleMap;

    googleMap.setOnMarkerClickListener(this);

    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Ancona, 5));
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM