5

I'm developing a android app with google maps. Currently I'm able to view the map inside my app, but I don't know how to view the current location on the app.

Here is my code:

public class MapsFragment 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_near_me, container, false);
            m = (MapView) v.findViewById(R.id.map);
            m.onCreate(savedInstanceState);
            return v;
        }
}

Edited: And the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map" />

</LinearLayout>

This code works fine and I got to know 'setmylocationenabled' can help to enable in FragmentActivity, but unfortunately I have to use the type as 'Fragment'. And I'm using google api v2. Please someone help with this.

Rachit Mishra
  • 6,031
  • 4
  • 28
  • 50
Kabe
  • 223
  • 2
  • 4
  • 15

5 Answers5

9

How about using the newly introduced fused location provider as referenced from: http://developer.android.com/training/location/retrieve-current.html

public static class XYZ extends Fragment
            implements
                GooglePlayServicesClient.ConnectionCallbacks,
                GooglePlayServicesClient.OnConnectionFailedListener,
                LocationListener {
        GoogleMap map;
        LatLng latlng;
        private LocationRequest lr;
        private LocationClient lc;
        MapFragment mapFragment;
        ImageView iv;
        private static View view;

        public XYZ() {
        }

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

            if (view != null) {
                ViewGroup parent = (ViewGroup) view.getParent();
                if (parent != null)
                    parent.removeView(view);
            }

            try {
                view = inflater.inflate(R.layout.XYZ, container,
                        false);

                mapFragment = ((MapFragment) this.getActivity()
                        .getFragmentManager().findFragmentById(R.id.map));
                iv = (ImageView) view.findViewById(R.id.iv);

                map = mapFragment.getMap();
                map.getUiSettings().setAllGesturesEnabled(false);
                map.getUiSettings().setMyLocationButtonEnabled(false);
                map.setMyLocationEnabled(true);
                map.getUiSettings().setZoomControlsEnabled(false);

                MapsInitializer.initialize(this.getActivity());
            } catch (GooglePlayServicesNotAvailableException e) {
                Toast.makeText(getActivity(), "Google Play Services missing !",
                        Toast.LENGTH_LONG).show();
            } catch (InflateException e) {
                Toast.makeText(getActivity(), "Problems inflating the view !",
                        Toast.LENGTH_LONG).show();
            } catch (NullPointerException e) {
                Toast.makeText(getActivity(), "Google Play Services missing !",
                        Toast.LENGTH_LONG).show();
            }

            return view;
        }
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            lr = LocationRequest.create();
            lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            lc = new LocationClient(this.getActivity().getApplicationContext(),
                    this, this);
            lc.connect();
        }

        @Override
        public void onLocationChanged(Location l2) {
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                    new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
            map.animateCamera(cameraUpdate);
        }

        @Override
        public void onConnectionFailed(ConnectionResult arg0) {

        }

        @Override
        public void onConnected(Bundle connectionHint) {
            lc.requestLocationUpdates(lr, this);

        }

        @Override
        public void onDisconnected() {

        }
    }

With the XML as:

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginBottom="4dp"
                android:layout_weight="1" >

                    <fragment
                        android:id="@+id/map"
                        android:name="com.google.android.gms.maps.MapFragment"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        />

                    <ImageView
                        android:id="@+id/iv"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@android:color/transparent" />

            </RelativeLayout>

You may get a blank map if you don't have all the requirements, https://developers.google.com/maps/documentation/android/start

  1. Get Play services on your project by following this post https://blog-emildesign.rhcloud.com/?p=435

  2. Then get an api key: https://blog-emildesign.rhcloud.com/?p=403

  3. Add the permissions to you manifest,

       <uses-permission android:name="your.application.package.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" />
    
  4. To test the map application you need to have a real device, if not then push play services to emulator via adb, read this post to learn how to install play services via adb https://stackoverflow.com/a/13869332/826657

  5. After all steps above, clean your project, uninstall the previous .apk from emulator, and run the project.

Community
  • 1
  • 1
Rachit Mishra
  • 6,031
  • 4
  • 28
  • 50
  • can you please provide your xml as well. – Kabe Aug 30 '13 at 12:57
  • Getting redflag at getSupportFragmentManager() 'The method getSupportFragmentManager() is undefined for the type Activity' – Kabe Aug 30 '13 at 13:16
  • i edited the code, try using `getFragmentManager()`, change all `SupportMapFragment` `to MapFragment`, in yur xml too change it to MapFragment from SupportMapFragment – Rachit Mishra Aug 30 '13 at 13:20
  • Sorry for late reply. But I'm getting blank white screen when I run it and in my LogCat: 09-01 13:01:02.760: E/GooglePlayServicesUtil(12622): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included. But I added all the required permissions in the manifest. – Kabe Sep 01 '13 at 12:04
  • Thanks for your answer, I followed all the steps you said and tested on real device. But still same results and the above code (posted by me) shows the map properly. I think there should be some other problems. Need more help please. – Kabe Sep 01 '13 at 14:36
  • @twnee: in your code I'm changing your code 'public static class XYZ extends Fragment' to 'public class XYZ extends Fragment'. Because It's showing redflag for me. Is that coursing this problem? and can you provide the imports for the XYZ file. – Kabe Sep 01 '13 at 14:43
  • no that's not causing the problem, actually that was an static inner class inside my fragment activity !, so you got the google play servics to your project.. check... you got the api key and added it to manifest.. check.. you switched on the Android Maps Api from console... check... you added all the permissions to your manifest... check... your real device has the Google Play services.. check... Uninstall the app from real device and try again. – Rachit Mishra Sep 01 '13 at 14:48
  • oki. but how. I don't hav enough reputation chat, may be skype? – Kabe Sep 01 '13 at 15:27
  • twnee I havn't got any reply on Hangout. And can you answer this question is possible: http://stackoverflow.com/questions/18558084/how-to-implement-asynctask-in-fragment – Kabe Sep 01 '13 at 15:52
7

You can enable your location just add this code in your class

 GoogleMap.setMyLocationEnabled(true);
Murali Ganesan
  • 2,815
  • 4
  • 18
  • 29
3

Here is the Link explains all the things you need

https://developers.google.com/maps/documentation/android/map

To set location on Map, you need to use below class

LatLong objLatLng=new LatLong(lat,longi);
yourMapObject.moveCamera(CameraUpdateFactory.newLatLngZoom(objLatLng, 20));
yourMapObject.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);

Hope this will help you.

Ripal Tamboli
  • 552
  • 1
  • 4
  • 16
2

You should init your Map v2 like this:

m = (MapView) v.findViewById(R.id.map);
GoogleMap mMap = m.getMap();

Now you can use mMap.setMyLocationEnabled(true);

Steve Benett
  • 12,633
  • 7
  • 55
  • 77
  • 1
    Tried but force close. CatLog: 08-30 13:26:48.635: D/AndroidRuntime(11455): Shutting down VM 08-30 13:26:48.635: W/dalvikvm(11455): threadid=1: thread exiting with uncaught exception (group=0x4164a2a0) 08-30 13:26:48.635: E/AndroidRuntime(11455): FATAL EXCEPTION: main 08-30 13:26:48.635: E/AndroidRuntime(11455): java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to com.google.android.gms.maps.MapView – Kabe Aug 30 '13 at 12:29
0
Use LocationListener:

       GPSTracker objGPSTracker = new GPSTracker(mContext);
            objGPSTracker.stopUsingGPS();
            objGPSTracker.getLocation();

This is class for GPSTracker

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;
    //
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 50; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        //getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            Constant.mLocation = location;
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            Constant.mLocation = location;
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    public void onLocationChanged(Location location) {
        Constant.mLocation = location;

    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}
Shivang Trivedi
  • 2,192
  • 1
  • 19
  • 26