24

I'm trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can't get the expected output. Also I'm a beginner on this platform! What I really want is just a way to put a map from the Google Maps API V2 for Android in a fragment. Please share your ideas and references.

Thanks in Advance !

MohanRaj S
  • 1,958
  • 4
  • 30
  • 54
Seïfane Idouchach
  • 620
  • 2
  • 5
  • 21
  • 3
    Possible duplicate of [How to put Google Maps V2 on a Fragment Using ViewPager](http://stackoverflow.com/questions/19353255/how-to-put-google-maps-v2-on-a-fragment-using-viewpager) – Mogsdad Mar 01 '16 at 19:47

11 Answers11

32

Here is the 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;
    }

Your layout,

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

Make some changes in your manifest file also.Like,

    <?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> 
Vipul Purohit
  • 9,807
  • 6
  • 53
  • 76
Basim Sherif
  • 5,384
  • 7
  • 48
  • 90
  • I'm trying to put the map in a Fragment here you're doing it in a Activity ! – Seïfane Idouchach Jun 07 '13 at 07:11
  • 6
    Eclipse is giving me this error : "Cannot cast from Fragment to MapFragment" – Seïfane Idouchach Jun 07 '13 at 07:19
  • try extending to FragmentActivity instead of Fragment – Basim Sherif Jun 07 '13 at 07:21
  • 1
    In this case I can't because I'm using the Master/Flow details Sample and this Fragment is used in a FragmentActivity. – Seïfane Idouchach Jun 07 '13 at 07:24
  • Also if I change from Fragment to FragmentActivity then a lot more of error are showing up ! – Seïfane Idouchach Jun 07 '13 at 07:25
  • 6
    Thanks a lot it finnaly worked ! You should edit your layout code to make the fragment with this class ' class="com.google.android.gms.maps.SupportMapFragment"' – Seïfane Idouchach Jun 07 '13 at 07:32
  • @SeïfaneIdouchach: please refer this http://stackoverflow.com/questions/16959083/android-map-v2-not-works-in-emulator-errors-are-occurred-in-log-cat/16959187#16959187 – Suraj Jun 07 '13 at 07:54
  • App crashes at map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap();. I guess the getFragmentManager() return null. – Bagusflyer Dec 04 '13 at 09:07
  • So, have you ever tried to add this fragment twice. It will crash at second time.. – Onuray Sahin Dec 05 '13 at 22:12
  • 1
    Yes this crashes when you try and add it the second time. You need to add some code to onDestroyView() to clean things up. But I am not sure the proper way to clean it. Anyone??? – lostintranslation Apr 07 '14 at 19:05
  • @lostintranslation ugh - stackoverflow fail... I've answered your question in a proper answer. – Todd DeLand Oct 06 '14 at 00:28
  • 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 Aug 07 '15 at 19:46
  • 1
    I've implemented this code before, when I upgrade play-service version to 4.3+ into android studio it crash every time like @PauloRoberto said in previous, other wise it work fine before in eclipse build. Have you any solutions for implementing GoogleMap into a fragment? – biswajitGhosh Aug 17 '15 at 15:50
  • 1
    @biswajitGhosh any luck on adding a map to Fragment? Getting same crash as you – user1406716 Jan 20 '16 at 07:30
  • 2
    There is a call getChildFragmentManager(), so you should use that instead of getFragmentManager() when you are dealing with fragments inside of a fragment. – smiki Feb 24 '16 at 13:06
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) {

    }

}

in 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" />
Vaishali Sutariya
  • 5,093
  • 30
  • 32
  • I tried this, but the map=mapView.getMap(); always returns a null, where as i have the mapView defined in my fragment layout, why is it happening ? – Sujal Mandal Aug 09 '14 at 05:35
  • have u implement mapView = (MapView) view.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); ?? or plz upload ur code – Vaishali Sutariya Aug 11 '14 at 09:20
  • Yeah its fixed, i was doing it the wrong way i was putting it in a method which was not getting called :D Thanks for your help. Though i couldn't manage to put gmap api inside another fragment, i got a work around. – Sujal Mandal Aug 11 '14 at 17:44
7

Update 10/24/2014 This is all wrong. You shouldn't have a fragment in a fragment. Rather you should extend the SupportMapFragment. See this stackoverflow post for some details: https://stackoverflow.com/a/19815266/568197

here is my onDestroyView()

public void onDestroyView() {
    super.onDestroyView();
    if (mMap != null) {
        getFragmentManager()
                .beginTransaction()
                .remove(getFragmentManager().findFragmentById(R.id.map))
                .commit();
    }
}
Community
  • 1
  • 1
Todd DeLand
  • 3,065
  • 1
  • 26
  • 15
3

in addition to the answer above, I also had to put the following lines to my manifest

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

And I also changed the layout to use SupportMapFragment instead of MapFragment

<fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
André Herculano
  • 1,258
  • 20
  • 33
2

Use SupportMapFragment instead of MapFragment and use getActivity()

This is a basic example using 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);
    }
}

and change the reference in your layout:

<fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
Community
  • 1
  • 1
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • how to do this in when fragment is getting added dynamically – Kaveesh Kanwal Jun 06 '16 at 07:28
  • 5
    Isn't this using an Activity when the user asked for implementation in a Fragment? – FlameDra Mar 09 '17 at 06:19
  • 1
    "Isn't this using an Activity when the user asked for implementation in a Fragment?" : Is that the reason for the -1?, remember **A Fragment is always contained inside an Activity**. – Jorgesys Jul 25 '17 at 23:47
2

Here is my code.

Create project in google map concole and generate api key.

and then add dependency to 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'

remember to add permissions in 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"/>

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

nothing to call from MainActivity.class

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

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

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

Hope this will help you :-)

Firdosh
  • 352
  • 5
  • 12
1

For all those friends who are facing the problem:-

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

Please try integrate GoogleMap using code

FragmentManager fm = getChildFragmentManager();
googleMap = ((SupportMapFragment)fm.findFragmentById(R.id.googleMap)).getMap();
Harpreet
  • 2,990
  • 3
  • 38
  • 52
0

I've the same issue , I use this code but I still get this error : unable to instantiate fragment com.google.android.gsm.SupportMapFragment: make sure class name exists ,is public, and has empty construct or that is public

I solved it from here : How to put Google Maps V2 on a Fragment Using ViewPager

Community
  • 1
  • 1
user3579994
  • 131
  • 1
  • 4
  • 12
0

If you are using android studio create google mapsactivity its default map fragment and generate your map API KEY and do your stuff......

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

and our override method

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

This example was build from the auto generated code from android studio, you dont need to change nothing in maps activity, only the context in the layout file to match your maps Activity

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

Using MapView within Fragment under Google Maps Android API v2.0

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

Kishan Donga
  • 2,851
  • 2
  • 23
  • 35
Sanjeev Kumar
  • 193
  • 1
  • 7