在片段中添加 Google Maps API V2

Posted

技术标签:

【中文标题】在片段中添加 Google Maps API V2【英文标题】:Add Google Maps API V2 in a fragment 【发布时间】:2013-06-03 09:52:57 【问题描述】:

我正在尝试在片段中显示来自 Google Maps API V2 的地图。我尝试使用 SupportMapFragment,但无法获得预期的输出。 我也是这个平台的初学者!我真正想要的只是一种将来自 Google Maps API V2 for android 的地图放入片段中的方法。请分享您的想法和参考。

提前致谢!

【问题讨论】:

How to put Google Maps V2 on a Fragment Using ViewPager的可能重复 【参考方案1】:

这是代码,

public class YourFragment extends Fragment 
    // ...
  static final LatLng HAMBURG = new LatLng(53.558, 9.927);
          static final LatLng KIEL = new LatLng(53.551, 9.993);
          private GoogleMap map;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 

        View v = inflater.inflate(R.layout.yourlayout, null, false);

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

Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
                .title("Hamburg"));
            Marker kiel = map.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_launcher)));

            // Move the camera instantly to hamburg with a zoom of 15.
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

            // Zoom in, animating the camera.
            map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

        //...

        return v;
    

你的布局,

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_
        android:layout_
        class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

还要对清单文件进行一些更改。比如,

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapp.android.locationapi.maps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <permission
        android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="com.myapp.android.locationapi.maps.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.myapp.android.locationapi.maps.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_apikey" />
    </application>

</manifest> 

【讨论】:

Eclipse 给我这个错误:“无法从 Fragment 转换为 MapFragment” 在这种情况下我不能这样做,因为我正在使用 Master/Flow details Sample 并且此 Fragment 用于 FragmentActivity。 非常感谢它终于奏效了!您应该编辑布局代码以使用此类'class="com.google.android.gms.maps.SupportMapFragment"'制作片段 java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference 有一个调用 getChildFragmentManager(),所以在处理片段内部的片段时应该使用它而不是 getFragmentManager()。【参考方案2】:
public class DemoFragment extends Fragment 


MapView mapView;
GoogleMap map;
LatLng CENTER = null;

public LocationManager locationManager;

double longitudeDouble;
double latitudeDouble;

String snippet;
String title;
Location location;
String myAddress;

String LocationId;
String CityName;
String imageURL;

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

    mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

  setMapView();


 

 private void setMapView() 
    try 
        MapsInitializer.initialize(getActivity());

        switch (GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity())) 
        case ConnectionResult.SUCCESS:
            // Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
            // .show();

            // Gets to GoogleMap from the MapView and does initialization
            // stuff
            if (mapView != null) 

                locationManager = ((LocationManager) getActivity()
                        .getSystemService(Context.LOCATION_SERVICE));

                Boolean localBoolean = Boolean.valueOf(locationManager
                        .isProviderEnabled("network"));

                if (localBoolean.booleanValue()) 

                    CENTER = new LatLng(latitude, longitude);

                 else 

                
                map = mapView.getMap();
                if (map == null) 

                    Log.d("", "Map Fragment Not Found or no Map in it!!");

                

                map.clear();
                try 
                    map.addMarker(new MarkerOptions().position(CENTER)
                            .title(CityName).snippet(""));
                 catch (Exception e) 
                    e.printStackTrace();
                

                map.setIndoorEnabled(true);
                map.setMyLocationEnabled(true);
                map.moveCamera(CameraUpdateFactory.zoomTo(5));
                if (CENTER != null) 
                    map.animateCamera(
                            CameraUpdateFactory.newLatLng(CENTER), 1750,
                            null);
                
                // add circle
                CircleOptions circle = new CircleOptions();
                circle.center(CENTER).fillColor(Color.BLUE).radius(10);
                map.addCircle(circle);
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            
            break;
        case ConnectionResult.SERVICE_MISSING:

            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:

            break;
        default:

        
     catch (Exception e) 

    


在片段布局中

<com.google.android.gms.maps.MapView
                android:id="@+id/mapView"
                android:layout_
                android:layout_                    
                android:layout_marginRight="10dp" />

【讨论】:

我试过这个,但是 map=mapView.getMap();总是返回一个空值,因为我在片段布局中定义了 mapView,为什么会这样? 让你实现 mapView = (MapView) view.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); ??或者请上传你的代码 是的,它已修复,我做错了,我把它放在一个没有被调用的方法中:D 感谢您的帮助。虽然我无法将 gmap api 放入另一个片段中,但我得到了解决方法。【参考方案3】:

2014 年 10 月 24 日更新这完全错了。您不应该在片段中有片段。相反,您应该扩展 SupportMapFragment。有关详细信息,请参阅此 *** 帖子:https://***.com/a/19815266/568197

这是我的 onDestroyView()

public void onDestroyView() 
    super.onDestroyView();
    if (mMap != null) 
        getFragmentManager()
                .beginTransaction()
                .remove(getFragmentManager().findFragmentById(R.id.map))
                .commit();
    

【讨论】:

最后正是我在这些无用的黑客中寻找的东西,:) 谢谢。【参考方案4】:

除了上面的答案,我还必须在清单中添加以下几行

<!-- inside <aplication> tag -->    
<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

我还更改了布局以使用SupportMapFragment 而不是MapFragment

<fragment
        android:id="@+id/map"
        android:layout_
        android:layout_
        class="com.google.android.gms.maps.SupportMapFragment" />

【讨论】:

【参考方案5】:

使用SupportMapFragment 代替MapFragment 并使用getActivity()

这是一个使用 SupportMapFragment 的基本示例:

public class MainActivity extends ActionBarActivity implements OnMapReadyCallback
    
    private SupportMapFragment map;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        map = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        map.getMapAsync(this);//remember getMap() is deprecated!      
    

    @Override
    public void onMapReady(GoogleMap map) 
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(
            new LatLng(47.17, 27.5699), 16));
        map.addMarker(new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher))
            .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
            .position(new LatLng(47.17, 27.5699))); //Iasi, Romania
        map.setMyLocationEnabled(true);
    

并更改布局中的引用:

<fragment
        android:id="@+id/map"
        android:layout_
        android:layout_
        class="com.google.android.gms.maps.SupportMapFragment" />

【讨论】:

如何在动态添加片段时执行此操作 当用户要求在Fragment中实现时,这不是使用Activity吗? "当用户要求在Fragment中实现时,这不是使用Activity吗?" : 这就是-1的原因吗?记住Fragment总是包含在Activity中【参考方案6】:

致所有遇到问题的朋友:-

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()

请尝试使用代码集成 GoogleMap

FragmentManager fm = getChildFragmentManager();
googleMap = ((SupportMapFragment)fm.findFragmentById(R.id.googleMap)).getMap();

【讨论】:

【参考方案7】:

这是我的代码。

在google map concole中创建项目并生成api key。

然后添加依赖到 build.gradle(app level)。

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'

记得在 Android.manifest 中添加权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-feature android:name="android.hardware.location.gps" android:required="true"/>

创建activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_
    android:layout_
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <fragment
        class="com.googlelocationmapdemo.FragmentLocation"
        android:layout_
        android:layout_ />
</FrameLayout>

没有可从 MainActivity.class

调用的内容

创建fragment_location.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearMap"
    android:layout_
    android:layout_>

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_
        android:layout_ />
</LinearLayout>

创建FragmentLocation.class

public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener 

    public static final String TAG = FragmentLocation.class.getSimpleName();
    public static final int REQUEST_CODE_FOR_PERMISSIONS = 1;
    GoogleApiClient mGoogleApiClient;
    LatLng mLatLng;
    GoogleMap mGoogleMap;
    Marker mCurrLocationMarker;
    private LinearLayout linearMap;
    Location mLastLocation;
    LocationManager locationManager;
    boolean statusOfGPS;
    private Dialog mDialogGPS;
    View view;
    LocationRequest mLocationRequest;
    SupportMapFragment mFragment;
   FragmentManager fragmentManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 

        view=inflater.inflate(R.layout.fragment_location,container,false);
        fragmentManager=getChildFragmentManager();
        mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
        mFragment.getMapAsync(this);
        if (!isGooglePlayServicesAvailable()) 
            Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show();
        
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return view;
    

    @Override
    public void onConnected(Bundle bundle) 
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000); //5 seconds
        mLocationRequest.setFastestInterval(2000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) 
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        
    

    @Override
    public void onConnectionSuspended(int i) 
    

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) 
    

    @Override
    public void onLocationChanged(Location location) 
        mLastLocation = location;
        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        
        mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(mLatLng);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
        // Zoom in the Google Map
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        mGoogleMap = googleMap;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) 
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);

             else 
                requestPermissions(new String[]Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_FINE_LOCATION,
                        REQUEST_CODE_FOR_PERMISSIONS);
            
         else 
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        

        //show dialog when click on location top-right side located on map.
        mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() 
            @Override
            public boolean onMyLocationButtonClick() 
                statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (!statusOfGPS) 
                    turnOnGps();
                 else 
                    getCurrentLocation(mLastLocation);
                
                return false;
            
        );
    

    private boolean isGooglePlayServicesAvailable() 
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (ConnectionResult.SUCCESS == status) 
            return true;
         else 
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        
    

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) 
            case REQUEST_CODE_FOR_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                    if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED &&
                            getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                                    == PackageManager.PERMISSION_GRANTED) 
                        if (mGoogleApiClient == null) 
                            buildGoogleApiClient();
                        
                        mGoogleMap.setMyLocationEnabled(true);
                    

                 else 
                    if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) 
                        Snackbar snackbar = Snackbar.make(linearMap, "Never asked"
                                , Snackbar.LENGTH_INDEFINITE);
                        snackbar.setAction("Allow", new View.OnClickListener() 
                            @Override
                            public void onClick(View view) 
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            
                        );
                        snackbar.show();
                    
                
                break;
        
    

    private void getCurrentLocation(Location location) 

        mLastLocation = location;

        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        
        if (locationManager != null) 
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) 
                mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location
            
            if (mLastLocation != null) 
                if (mGoogleMap != null) 
                    Log.d("activity", "LOC by Network");
                    mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(mLatLng);
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
                    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                
            
        
    

    private void turnOnGps() 
        if (mGoogleMap != null) 
            mGoogleMap.clear();
        
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off.
        mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme);
        mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialogGPS.setContentView(R.layout.dialog_turnongps);
        TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel);
        TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting);

        ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation);

        imgLocation.setImageResource(R.drawable.ic_location_my);

        txtCancel.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                mDialogGPS.dismiss();
                //finish();
                if (!statusOfGPS) 
                    getCurrentLocationByDefault();
                 else 
                    getCurrentLocation(mLastLocation);
                
            
        );

        txtOK.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                //It is use to redirect to setting->location to turn on gps when press ok.
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                mDialogGPS.dismiss();
                if (!statusOfGPS) 
                    getCurrentLocationByDefault();
                 else 
                    getCurrentLocation(mLastLocation);
                
            
        );
        mDialogGPS.show();
    

    private void getCurrentLocationByDefault() 
        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        

        if (mGoogleMap != null) 
            LatLng xFrom1 = new LatLng(0.0, 0.0);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0));

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(xFrom1);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi));
            mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
         else 
            Log.i("MainActivity", "getCurrentLocationByDefault else");
        

    

    @Override
    public void onResume() 
        super.onResume();
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (mDialogGPS != null) 
            if (mDialogGPS.isShowing()) 
                mDialogGPS.dismiss();
            
        
        if (!statusOfGPS) 
            turnOnGps();
         else 
            getCurrentLocation(mLastLocation);
        

    
    protected synchronized void buildGoogleApiClient() 
        if (mGoogleApiClient != null) 
            mGoogleApiClient = null;
        
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    

创建dailog_gps.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:padding="20dp"
    android:orientation="vertical">


    <LinearLayout

        android:layout_
        android:layout_
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtPhoneNumber"
            android:layout_
            android:layout_
            android:text="Use Location?"
            android:textColor="@android:color/black"
          android:textSize="16sp"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="15dp"
        android:layout_
        android:layout_
        android:orientation="horizontal">

        <TextView
            android:layout_
            android:layout_
            android:layout_weight="1"
            android:text="This app wants to change your \ndevice settings:"
            android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="10dp"
        android:weightSum="2"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_
        android:layout_>

        <ImageView
            android:id="@+id/imgLocation"
            android:layout_weight="1"
            android:layout_gravity="top"
            android:layout_
            android:layout_ />

        <TextView
            android:layout_weight="1"
            android:layout_
            android:layout_
            android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
            android:layout_marginLeft="20dp"
            android:textSize="12sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_
        android:layout_
        android:layout_gravity="right"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <TextView
            android:id="@+id/txtCancel"
            android:layout_
            android:layout_
            android:text="NO"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/txtSetting"
            android:layout_
            android:layout_
            android:text="YES"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

    </LinearLayout>
</LinearLayout>

希望这会对你有所帮助:-)

【讨论】:

【参考方案8】:

我有同样的问题,我使用了这段代码,但我仍然得到这个错误: 无法实例化片段 com.google.android.gsm.SupportMapFragment:确保类名存在、是公开的、具有空结构或公开的

我从这里解决了:How to put Google Maps V2 on a Fragment Using ViewPager

【讨论】:

【参考方案9】:

如果您使用 android studio 创建 google mapsactivity 它的默认地图片段并生成您的地图 API KEY 并做您的事情......

SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this);

还有我们的覆盖方法

public void onMapReady(GoogleMap googleMap)

   mMap = googleMap;
   LatLng map = new LatLng(lat, lon);
   mMap.addMarker(new MarkerOptions().position(map).title("your title"));
   mMap.animateCamera(CameraUpdateFactory.newLatLng(map));
   mMap.setMapType(GoogleMap.MAP_TYPE_NONE);


【讨论】:

【参考方案10】:

这个例子是从android studio自动生成的代码构建的,你不需要改变地图活动中的任何内容,只需布局文件中的上下文来匹配你的地图活动

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_
    android:layout_
    android:weightSum="1">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_
android:layout_
tools:context="com.gearwell.app.gpsmaps02.Gpsenmapa"

/>

<LinearLayout
    android:id="@+id/layButtonH"
    android:layout_
    android:layout_marginTop="50dp"
    android:layout_
    android:gravity="center"
    android:layout_weight="0.15">
    <Button
        android:layout_
        android:layout_
        android:text="Obtener Ubicacion"
        android:id="@+id/btnLocation"
        android:onClick="onClick"/>
</LinearLayout>
</LinearLayout>

【讨论】:

【参考方案11】:

在 Google Maps Android API v2.0 下的 Fragment 中使用 MapView

public class MapFragment extends Fragment 

    MapView m;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) 
        // inflat and return the layout
        View v = inflater.inflate(R.layout.map_fragment, container, false);
        m = (MapView) v.findViewById(R.id.mapView);
        m.onCreate(savedInstanceState);

        return v;
    

    @Override
    public void onResume() 
        super.onResume();
        m.onResume();
    

    @Override
    public void onPause() 
        super.onPause();
        m.onPause();
    

    @Override
    public void onDestroy() 
        super.onDestroy();
        m.onDestroy();
    

    @Override
    public void onLowMemory() 
        super.onLowMemory();
        m.onLowMemory();
    

http://ucla.jamesyxu.com/?p=287

【讨论】:

以上是关于在片段中添加 Google Maps API V2的主要内容,如果未能解决你的问题,请参考以下文章

Android : Google Maps API V2 显示黑屏 ECLIPSE

将 Google maps api v2 添加到现有项目

Google Maps API v2 自定义 MapFragment + SimpleFragment

添加大量标记时,Google Maps Android API v2 非常慢

在 Google Maps API v2 中更改标记大小

在 Google Maps Android API v2 中使用新的 OnMyLocationChangeListener