在一个片段中添加Google地图API V2

24
我试图在碎片中显示来自Google Maps API V2的地图。我尝试使用SupportMapFragment,但是我无法获得期望的输出。我是这个平台上的初学者!我真正想要的只是一种将Android中来自Google Maps API V2的地图放入碎片中的方法。请分享您的想法和参考资料。
先感谢您!

3
可能是如何在ViewPager中使用Fragment放置Google Maps V2的重复问题。 - Mogsdad
11个回答

32

这是代码,

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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        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> 

6
Eclipse 给了我这个错误提示:"无法将 Fragment 强制转换为 MapFragment"。 - Seïfane Idouchach
6
非常感谢,终于成功了!您应该编辑布局代码,将具有以下类 'class="com.google.android.gms.maps.SupportMapFragment"'的片段。 - Seïfane Idouchach
1
是的,当您尝试第二次添加它时,它会崩溃。您需要添加一些代码到onDestroyView()中来清理它。但我不确定正确的清理方式。有人可以提供帮助吗? - lostintranslation
2
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 - Paulo Roberto Rosa
2
有一个调用getChildFragmentManager()的方法,所以当您在处理嵌套的片段时,应该使用它而不是getFragmentManager()。 - smiki
显示剩余10条评论

8
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) {

    }

}

在 fragment_layout 中

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

我尝试了这个,但是mapView.getMap()始终返回null,而我在我的fragment布局中定义了mapView,为什么会这样发生? - Sujal Mandal
你是否已经实现了以下代码:mapView = (MapView) view.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); ??或者请上传你的代码。 - Vaishali Sutariya
是的,问题已经解决了。我之前的做法有误,把代码放在一个没有被调用的方法里面了 :D 感谢你的帮助。虽然我没能把GMap API放在另一个片段中,但我找到了一个解决办法。 - Sujal Mandal

7

更新于2014年10月24日,这全都是错的。您不应该在片段中使用片段。相反,您应该扩展SupportMapFragment。有关详细信息,请参见此stackoverflow帖子:https://dev59.com/Qeo6XIcBkEYKwwoYOR0q#19815266

这是我的onDestroyView()

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

1
最后终于找到我在这些无用的 hack 中寻找的东西了,:) 谢谢。 - Adam Varhegyi

3

除了上面的答案,我还需要将以下行添加到我的清单中

<!-- 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_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

2

使用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_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />

当片段动态添加时,如何处理? - Kaveesh Kanwal
5
用户要求在Fragment中实现,但这不是在使用Activity吗?请问是否正确? - FlameDra
1
“当用户要求在片段中实现时,这不是使用 Activity 吗?”:这是-1的原因吗?请记住片段始终包含在活动中 - Jorgesys

2

以下是我的代码。

在Google地图控制台中创建项目并生成API密钥。

然后将依赖项添加到build.gradle(应用程序级别)中。

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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <fragment
        class="com.googlelocationmapdemo.FragmentLocation"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

无法从MainActivity.class中调用任何内容。

创建fragment_location.xml文件。

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

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</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_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:orientation="vertical">


    <LinearLayout

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

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

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            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_width="match_parent"
        android:layout_height="wrap_content">

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

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

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

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

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

    </LinearLayout>
</LinearLayout>

希望这能帮到你 :-)

1

对于所有遇到以下问题的朋友:

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();

0
如果您正在使用Android Studio创建Google MapsActivity,则默认使用地图片段并生成您的地图API密钥,然后进行操作......
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);

}

0

在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


0

这个示例是从Android Studio自动生成的代码构建的,您不需要更改地图活动中的任何内容,只需在布局文件中更改上下文以匹配您的地图活动即可。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    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_width="match_parent"
android:layout_height="300dp"
tools:context="com.gearwell.app.gpsmaps02.Gpsenmapa"

/>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接