Search code examples
androidgoogle-maps-api-3android-mapviewandroid-maps

Mark current location on google map


How to mark my current location on google map?

I am using google place API. I have to show all near places from my current position. All places are showing on google map, but how to show my current position? The code is given below:

public class PoliceStationMapActivity extends FragmentActivity implements LocationListener {
    private ArrayList<Place> mArrayListPoliceStations;
    private GoogleMap mMap;
    private LocationManager locManager;
    private double latitude;
    private double longitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_police_station);

    locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    else
        Log.i("Test", "network provider unavailable");

    Location lastKnownLocation = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    latitude = lastKnownLocation.getLatitude();
    longitude = lastKnownLocation.getLongitude();

    if (lastKnownLocation != null) {
        Log.i("Test", lastKnownLocation.getLatitude() + ", " + lastKnownLocation.getLongitude());
        locManager.removeUpdates(this);
    }

    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    if (mMap != null) {
        new GetAllPoliceStationsTask().execute("" + latitude, "" + longitude);
    }
}

private class GetAllPoliceStationsTask extends AsyncTask<String, Void, ArrayList<Place>> {
    @Override
    protected ArrayList<Place> doInBackground(String... param) {
        ArrayList<Place> policeStationsList = RequestHandler.getInstance(PoliceStationMapActivity.this).getAllPlaces(param[0], param[1]);
        return policeStationsList;
    }

    @Override
    protected void onPostExecute(java.util.ArrayList<Place> result) {
        if (result != null) {
            mArrayListPoliceStations = result;
            placeAllPoliceStationMarkersOnMap(mArrayListPoliceStations);
        }
    }

}

private void placeAllPoliceStationMarkersOnMap(ArrayList<Place> policeStationList) {
    for (Place place : policeStationList) {
        addPlaceMarkerOnMap(place);
    }
};

private void addPlaceMarkerOnMap(Place place) {
    LatLng latLng = new LatLng(place.getLatitude(), place.getLongitude());
    Marker poiMarker = mMap.addMarker(new MarkerOptions().position(latLng).title(place.getName()).snippet(place.getVicinity()));
    Marker currentMarker = mMap.addMarker(new MarkerOptions().position());
}

@Override
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {

}

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

}`

Solution

  • First, to obtain the current location:

    private Location mCurrentLocation;
    mCurrentLocation = mLocationClient.getLastLocation();
    

    Read here to know more.

    And then you can point to the location using:

    LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
    
    CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                    .zoom(15)
                    .bearing(45)
                    .tilt(70)
                    .build();
    
     CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
    
     map.animateCamera(camUpd3);
    

    I give you a simple but complete example to show a map and the current location:

    (Full project available in github.com/josuadas/LocationDemo )

    public class MainActivity extends FragmentActivity implements
            GooglePlayServicesClient.ConnectionCallbacks,
            GooglePlayServicesClient.OnConnectionFailedListener {
    
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    
        private LocationClient mLocationClient;
        private Location mCurrentLocation;
        private GoogleMap map;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.map);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            setUpMapIfNeeded();
            setUpLocationClientIfNeeded();
            mLocationClient.connect();
        }
    
        private void setUpMapIfNeeded() {
            // Do a null check to confirm that we have not already instantiated the
            // map.
            if (map == null) {
                // Try to obtain the map from the SupportMapFragment.
                map = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
                // Check if we were successful in obtaining the map.
                if (map == null) {
                    Toast.makeText(this, "Google maps not available",
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    
        private void setUpLocationClientIfNeeded() {
            if (mLocationClient == null) {
                Toast.makeText(getApplicationContext(), "Waiting for location",
                        Toast.LENGTH_SHORT).show();
                mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                        this); // OnConnectionFailedListener
            }
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if (mLocationClient != null) {
                mLocationClient.disconnect();
            }
        }
    
        /*
         * Called by Location Services when the request to connect the client
         * finishes successfully. At this point, you can request the current
         * location or start periodic updates
         */
        @Override
        public void onConnected(Bundle dataBundle) {
            mCurrentLocation = mLocationClient.getLastLocation();
            if (mCurrentLocation != null) {
                Toast.makeText(getApplicationContext(), "Found!",
                        Toast.LENGTH_SHORT).show();
                centerInLoc();
            }
        }
    
        private void centerInLoc() {
            LatLng myLaLn = new LatLng(mCurrentLocation.getLatitude(),
                    mCurrentLocation.getLongitude());
            CameraPosition camPos = new CameraPosition.Builder().target(myLaLn)
                    .zoom(15).bearing(45).tilt(70).build();
    
            CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);
            map.animateCamera(camUpd3);
    
            MarkerOptions markerOpts = new MarkerOptions().position(myLaLn).title(
                    "my Location");
            map.addMarker(markerOpts);
        }
    
        /*
         * Called by Location Services if the connection to the location client
         * drops because of an error.
         */
        @Override
        public void onDisconnected() {
            // Display the connection status
            Toast.makeText(this, "Disconnected. Please re-connect.",
                    Toast.LENGTH_SHORT).show();
        }
    
        /*
         * Called by Location Services if the attempt to Location Services fails.
         */
        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects. If the error
             * has a resolution, try sending an Intent to start a Google Play
             * services activity that can resolve error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this,
                            CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available
                 */
                Log.e("Home", Integer.toString(connectionResult.getErrorCode()));
            }
        }
    }
    

    Note1: I omitted the "Check for Google Play Services" part by simplicity but it should be added as a good practice.

    Note2: You need the google-play-services_lib project and reference it from yours.

    You can find all information about interacting with google maps in android here