Agregar Google Maps API V2 en un fragmento

Intento mostrar el mapa de la API V2 de Google Maps en fragmentos. Intenté con SupportMapFragment, pero no puedo obtener el resultado esperado. ¡También soy un principiante en esta plataforma! Lo que realmente quiero es solo una manera de poner un mapa de Google Maps API V2 para Android en un fragmento. Por favor comparta sus ideas y referencias.

Gracias por adelantado !

Utilice SupportMapFragment lugar de MapFragment y use getActivity()

Este es un ejemplo básico usando 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); } } 

y cambie la referencia en su diseño:

  

Aquí está el código,

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

Tu diseño,

     

Realice algunos cambios en su archivo de manifiesto también. Como,

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

en fragment_layout

  

Actualización 10/24/2014 Esto está todo mal. No deberías tener un fragmento en un fragmento. En su lugar, debe ampliar el SupportMapFragment. Consulte esta publicación de stackoverflow para obtener más información: https://stackoverflow.com/a/19815266/568197

aquí está mi onDestroyView ()

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

Además de la respuesta anterior, también tuve que poner las siguientes líneas en mi manifiesto

   

Y también cambié el diseño para usar SupportMapFragment lugar de MapFragment

  

Para todos aquellos amigos que enfrentan el problema:

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

Intente integrar GoogleMap usando el código

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

Aquí está mi código.

Cree un proyecto en la concole de google map y genere una clave de API.

y luego agregue dependencia a build.gradle (nivel de la aplicación).

 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' 

recuerda agregar permisos en Android.manifest

          

crear activity_main.xml

    

nada para llamar desde MainActivity.class

Crea fragment_location.xml

    

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

crear dailog_gps.xml

                 

Espero que esto te ayudará 🙂

Tengo el mismo problema, uso este código pero sigo recibiendo este error: no se puede crear una instancia del fragmento com.google.android.gsm.SupportMapFragment: asegúrese de que el nombre de clase exista, sea público y tenga una construcción vacía o que sea público

Lo resolví desde aquí: cómo poner Google Maps V2 en un fragmento usando ViewPager

Si está utilizando el estudio Android, cree google mapsactivity su fragmento de mapa predeterminado y genere su mapa API KEY y haga sus cosas …

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

y nuestro método de anulación

vacío público enMapReady (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); } 

Este ejemplo fue comstackdo a partir del código generado automáticamente desde android studio, no necesita cambiar nada en la actividad de los mapas, solo el contexto en el archivo de diseño para que coincida con sus mapas Activity

        

Usando MapView dentro de Fragment en Google Maps Android API v2.0

la clase pública 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