web-dev-qa-db-fra.com

Ajouter Google Maps API V2 dans un fragment

J'essaie de montrer la carte fragmentée de l'API Google Maps V2. J'ai essayé avec SupportMapFragment, mais je ne parviens pas à obtenir le résultat attendu ..__ également, je suis débutant sur cette plateforme! Ce que je veux vraiment, c’est juste un moyen de mettre une carte à partir de l’API Google Maps V2 pour Android dans un fragment. S'il vous plaît partager vos idées et vos références.

Merci d'avance !

24

Voici le code,

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;
    }

Votre mise en page,

 <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>

Apportez également des modifications dans votre fichier manifeste.

    <?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> 
32
Basim Sherif
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) {

    }

}

dans 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" />
8
Vaishali Sutariya

Mise à jour 24/10/2014 Tout cela est faux. Vous ne devriez pas avoir un fragment dans un fragment. Au lieu de cela, vous devriez étendre le SupportMapFragment. Voir cet article stackoverflow pour quelques détails: https://stackoverflow.com/a/19815266/568197

voici mon onDestroyView ()

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

en plus de la réponse ci-dessus, je devais également mettre les lignes suivantes à mon manifeste

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

Et j'ai aussi changé la mise en page pour utiliser SupportMapFragment au lieu de MapFragment

<fragment
        Android:id="@+id/map"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        class="com.google.Android.gms.maps.SupportMapFragment" />
3
André Herculano

Utilisez SupportMapFragment au lieu de MapFragment et utilisez getActivity()

Voici un exemple de base utilisant 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);
    }
}

et changez la référence dans votre mise en page:

<fragment
        Android:id="@+id/map"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        class="com.google.Android.gms.maps.SupportMapFragment" />
2
Elenasys

Voici mon code.

Créer un projet dans Google Map concole et générer une clé API.

puis ajoutez la dépendance à build.gradle (niveau de l'application).

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'

n'oubliez pas d'ajouter des autorisations dans 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"/>

créer 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>

rien à appeler depuis MainActivity.class

Créer 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>

Créer 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();
    }
}

créer 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>

J'espère que ceci vous aidera :-)

1
Firdosh

Pour tous ces amis qui font face au problème: -

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

S'il vous plaît essayez d'intégrer GoogleMap en utilisant le code

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

Utilisation de MapView dans Fragment sous API Google Maps Android v2.0

classe publique MapFragment étend 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
Sanjeev Kumar

J'ai le même problème, j'utilise ce code mais j'obtiens toujours l'erreur: Impossible d'instancier le fragment com.google.Android.gsm.SupportMapFragment: assurez-vous que le nom de la classe existe, est public et a une construction vide est public

Je l'ai résolu à partir de maintenant: Comment mettre Google Maps V2 sur un fragment à l'aide de ViewPager

0
user3579994

Cet exemple a été construit à partir du code généré automatiquement par Android Studio, vous ne devez rien changer à l'activité des cartes, seul le contexte du fichier de mise en page doit correspondre à vos cartes

<?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>

Si vous utilisez Android Studio, créez Google Mapsactivity avec son fragment de carte par défaut, générez votre clé API de carte et effectuez vos opérations ......

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

et notre méthode de substitution

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

}