Unable to see marker on map - android

Below is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.bustracker.usc.myapplication.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager manager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("INSIDE ONCREATE", "TRUE");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//get the location service
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
//request the location update thru location manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.d("BFORE ISPROVIDERENABLED", "TRUE");
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d("LATLNG", latitude+" " +longitude);
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}else if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//get the latitude and longitude from the location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getSubLocality() + ":";
result += addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryCode();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
protected void onPause() {
super.onPause();
manager.removeUpdates(locationListener);
Log.i("onPause...","paused");
}
}
Above is my MapsActivity.java,
I'm trying to getCurrentLocation and place the marker there.
When I run app I am unable to see the marker on my map. What went wrong?
Thanks for the help.

Try to create the markers and all things about the map inside the onMapReady method, if it doesn't work try seeing if you are getting your location properly
Hope it helps you, Pd: sorry for my english

Make sure you are getting valid latLng
OR
If you want to add custom icon to set marker add it like:
map.addMarker(new MarkerOptions().position(latLng).title(result)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

Related

double android.location.Location.getLatitude()' on a null object reference

the only reason i'm asking this again, is because i've tried all the answers and its not working for me i'm trying to get the current user location but it's not working so this is what i've been trying to do, btw i already setted up all the permissions neeeded and i keep getting the double android location.getlatitude on a null object reference error and fatal execption main , pleaaase help me
this my GPSTRACKER Java class code :
package com.example.nefissa.androidtest;
import android.*;
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
public class GPSTracker extends Service implements LocationListener{
private final Context context;
boolean isGPSEnabled =false;
boolean isNetworkEnabled =false;
boolean canGetLocation =false;
Location location;
protected LocationManager locationManager;
public GPSTracker(Context context){
this.context=context;
}
// create a GetLocation Method //
public Location getLocation(){
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);
if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){
if(isGPSEnabled){
if(location==null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,100000,10,this);
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
// if location is not found from GPS then it will found from network //
if(location==null){
if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100000,10,this);
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}
}
}catch(Exception e){
}
return location;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
and My Main Activity code :
package com.example.nefissa.androidtest;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GPSTracker gpsTracker;
private Location mLocation;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
gpsTracker= new GPSTracker(getApplicationContext());
mLocation=gpsTracker.getLocation();
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("you are here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
After onMapReady is called, you'd better to initialize gpsTracker.
gpsTracker= new GPSTracker(getApplicationContext());
if(gpsTracker!=null){
mLocation=gpsTracker.getLocation();
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
}
And I think gpsTracker.getLocation have to change to logic.
please read a android gps guide.
Try using
GPS Tracker
public GPSTracker(Activity activity) {
this.mActivity = activity;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled || !isNetworkEnabled) {
showSettingsAlert();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
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) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 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 ic_check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
also from Activity call as
onCreate
//
gps = new GPSTracker(SignUpActivity.this);
if (gps.canGetLocation) {
lat = String.valueOf(gps.getLatitude());
lng = String.valueOf(gps.getLongitude());
}
Comment below if you still got issue

Start map with current location

I want the map in this application to start with the current location of the user but it keeps starting with the default location being the location with latitude = 0 and longitude = 0.
It also doesn't work when I walk around with phone in hand..
This is my code:
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager locationManager;
private double longitude;
private double latitude;
public Criteria criteria;
public String bestProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getLocation();
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
protected void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Location"));
}
#Override
public void onLocationChanged(Location location) {
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
}
// ... other LocationListener methods that I left empty. I removed to shorten the code
}
}
Could you please tell me where's the problem? I've tried many fixes from StackOF but I couldn't get it to work.

how to set my google Map app to be show my current location as default? [duplicate]

Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also still I didn't get answer.Please help me
Code:
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
googleMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation(); //Nullpointer exception.........
LatLng myLatLng = new LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition = new CameraPosition.Builder()
.target(myLatLng).zoom(17).bearing(90).tilt(30).build();
googleMap.animateCamera(
CameraUpdateFactory.newCameraPosition(myPosition));
Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
}
});
}
}
}
Call this function in onCreate function.
Update:
The method mMap.setOnMyLocationChangeListener is now deprecated, you need to use the FusedLocationProviderClient now.
private FusedLocationProviderClient fusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
To request the last known location, call the getLastLocation() method. The following code snippet illustrates the request and a simple handling of the response:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
Reference: https://developer.android.com/training/location/retrieve-current.html
I think that better way now is:
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Documentation. Getting the Last Known Location
package com.example.sandeep.googlemapsample;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
private double longitude;
private double latitude;
private GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
// Add a marker in Sydney and move the camera
LatLng india = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
private void moveMap() {
/**
* Creating the latlng object to store lat, long coordinates
* adding marker to map
* move the camera with animation
*/
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onClick(View view) {
Log.v(TAG,"view click event");
}
#Override
public void onConnected(#Nullable Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
// mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
}
#Override
public void onMarkerDragStart(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDrag(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDragEnd(Marker marker) {
// getting the Co-ordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//move to current position
moveMap();
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MapsActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
return true;
}
}
If you don't need to retrieve the user's location every time it changes (I have no idea why nearly every solution does that by using a location listener), it's just wasteful to do so. The asker was clearly interested in retrieving the location just once. Now FusedLocationApi is deprecated, so as a replacement for #Andrey's post, you can do:
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// I suppressed the missing-permission warning because this wouldn't be executed in my
// case without location services being enabled
#SuppressLint("MissingPermission") android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double userLat = lastKnownLocation.getLatitude();
double userLong = lastKnownLocation.getLongitude();
This just puts together some scattered information in the docs, this being the most important source.
This Code in MapsActivity Class works for me :
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
public void centreMapOnLocation(Location location, String title){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Intent intent = getIntent();
if (intent.getIntExtra("Place Number",0) == 0 ){
// Zoom into users location
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location,"Your Location");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation,"Your Location");
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
}
}
}
Select google map activity
you need a Google Maps API key.
To get one, follow this link, follow the directions and press "Create" at the end:
https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication
Paste this Code in MapsActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implement
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
#private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
Make sure these permission are written in Manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Add following dependencies
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
Your current location might not be available immediately, after the map fragment is initialized.
After set
googleMap.setMyLocationEnabled(true);
you have to wait until you see the blue dot shown on your MapView. Then
Location myLocation = googleMap.getMyLocation();
myLocation won't be null.
I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)
Receiving Location Updates will show you how to get current location from LocationClient
Location locaton;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
mMap.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
mMap.addMarker(mp);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});}}
FusedLocationApi has been Deprecated (Why Google always deprecated everything!)
location: retrieve-current
Here is the way to get it now:
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
public void getMyLocation() {
// create class object
gps = new GPSTracker(HomeActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
postalCode = addresses.get(0).getPostalCode();
city = addresses.get(0).getLocality();
address = addresses.get(0).getAddressLine(0);
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
knownName = addresses.get(0).getFeatureName();
Log.e("Location",postalCode+" "+city+" "+address+" "+state+" "+knownName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
}
}
All solution mentioned above using that code which are deprecated now!Here is the new solution
Add implementation 'com.google.android.gms:play-services-places:15.0.1' dependency in your gradle file
Add network permission in your manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Now use this code to get current location
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
currentLat = location.getLatitude();
currentLong = location.getLongitude();
Toast.makeText(HomeNavigationBarActivtiy.this, "lat " + location.getLatitude() + "\nlong " + location.getLongitude(), Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
From Google Sample (CurrentPlaceDetailsOnMap) for kotlin by FusedLocationProviderClient in order to setOnMyLocationChangeListener is deprecated
at first add implementation 'com.google.android.libraries.places:places:2.4.0' to dependencies
next in your fragment add these variables
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
private var lastKnownLocation: Location? = null
next in onViewCreated add this
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireContext())
in onMapReady call this method
private fun getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
val locationResult = fusedLocationProviderClient.lastLocation
locationResult.addOnCompleteListener(context as Activity) { task ->
if (task.isSuccessful) {
// Set the map's camera position to the current location of the device.
lastKnownLocation = task.result
if (lastKnownLocation != null) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(lastKnownLocation!!.latitude,
lastKnownLocation!!.longitude), DEFAULT_ZOOM.toFloat()))
}
} else {
logD("Current location is null. Using defaults.")
logD("Exception: ${task.exception}")
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(35.6892, 51.3890), 15.toFloat()))
mMap.uiSettings?.isMyLocationButtonEnabled = false
}
}
} catch (e: SecurityException) {
logD("Exception: ${e.message}")
}
}
if lastKnownLocation be null you should update it with this method:
fun requestLocation(context: Context) {
val mLocationRequest = LocationRequest.create()
mLocationRequest.interval = 60000
mLocationRequest.fastestInterval = 5000
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val mLocationCallback: LocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
for (location in locationResult.locations) {
if (location != null && lastKnownLocation == null) {
lastKnownLocation = location
}
}
}
}
LocationServices.getFusedLocationProviderClient(context)
.requestLocationUpdates(mLocationRequest, mLocationCallback, null)
}
if you want, you can turn on your location by this
mMap.isMyLocationEnabled = true
mMap.uiSettings.isMyLocationButtonEnabled = false
Add the permissions to the app manifest
Add one of the following permissions as a child of the element in your Android manifest. Either the coarse location permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
Or the fine location permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
The following code sample checks for permission using the Support library before enabling the My Location layer:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_LOCATION_REQUEST_CODE) {
if (permissions.length == 1 &&
permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Permission was denied. Display an error message.
}
}
This example provides current location update using GPS provider. Entire Android app code is as follows,
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
Simple steps to get current location on google map:
1 - create map activity so in onMap ready method you create LocationManager and LocationListener
2 - in onMap ready also you check for android version and user permission ==> if there is a permission give location update OR ask the user for permission
3 - in the main class check for result of permission (onRequestPermissionsResult) ==> if the condition is true so give location update
4 - in (onLocationChanged) method we create LatLng variable and get the coordinates from location then from mMap we (addMarker and moveCamera) for that variable we've just created, this gives us location when the user moves so we still need to create new LatLng in onMap ready to have user's location when the App starts ==>inside condition if there is permission (lastKnownLocation).
NOTE:
1) Do Not forget to ask for permissions (Location and Internet) in Manifest
2) Do Not forget to have Map key from google APIs
3) We used (mMap.clear) to avoid repeating the marker each time we (run the app or update location)
Coding Part:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mMap.clear();
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23 ){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
}
}
//check this condition if (Build.VERSION.SDK_INT < 23 )
In some android studio it does not work while Whole code is working, so replace this line by this:
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
& my project is working fine.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private FusedLocationProviderClient client;
double latit;
double longi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
client = LocationServices.getFusedLocationProviderClient(this);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
setupMap();
} catch (IOException e) {
e.printStackTrace();
}
}
client = LocationServices.getFusedLocationProviderClient(this);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
client.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// local=findViewById(R.id.tv5);
double la=location.getLatitude();
double lo=location.getLongitude();
LatLng curre=new LatLng(la,lo);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curre,18));
}
}
});
}
}
Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient.
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private LocationListener mLocationListener;
private void initGoogleApiClient(Context context)
{
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
{
#Override
public void onConnected(Bundle bundle)
{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000);
setLocationListener();
}
#Override
public void onConnectionSuspended(int i)
{
Log.i("LOG_TAG", "onConnectionSuspended");
}
}).build();
if (mGoogleApiClient != null)
mGoogleApiClient.connect();
}
private void setLocationListener()
{
mLocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
String lat = String.valueOf(location.getLatitude());
String lon = String.valueOf(location.getLongitude());
Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
}
};
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}
private void removeLocationListener()
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}

requestLocationUpdates error

please I have a problem with my code:
import android.Manifest;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private static final int REQUEST_LOCATION = 2;
private Location myLocation;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public static final String TAG = MapsActivity.class.getSimpleName();
private LocationRequest mLocationRequest;
protected LocationManager locationManager;
protected LocationListener locationListener;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
// permission has been granted, continue as usual
Location myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
if (myLocation == null) {
Log.i(TAG, "Location services not enabled!");
} else {
handleNewLocation(myLocation);
}
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3 * 1000) // 3 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//Got aproblem with requestLocationUpdates !!!!
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions().position(latLng).title("I am here!");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
//handleNewLocation(myLocation);
}
#Override
public void onConnected(Bundle bundle) {
Location mLastLocation;
Log.i(TAG, "Location services connected.");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+"Longitude: "+location.getLongitude();
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
}
In this part exactly:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);
It says cannot resolve the method. I tried some "solutions" I found here, but none of them worked!
Can you help me please
dont pass this param;(remove implements LocationListener from that activity) instead do like this
LocationListener myLocationListener= new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("dj","on location changed: "+location.getLatitude()+" & "+location.getLongitude());
toastLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, myLocationListener);
private void toastLocation(final Location location){
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(ServiceProvide.this.getApplicationContext(),"Location latitude: "+ location.getLatitude()
+"longitude: "+location.getLongitude(), Toast.LENGTH_SHORT).show();
}
});
}

Error in marker options icon

I want to get the current location of the user by using Google Maps V2. I get this error, the method icon(bitmapdescriptor) is undefined for the type marker.
This is my code based on android + google map api v2 + current location
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else{ // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map object from the fragment
GoogleMap googleMap = fm.getMap();
// Enabling MyLocation Layer of Google
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting current location
Location location = locationManager.getLastKnownLocation(provider);
LocationListener locationListener = new LocationListener(){
public void onLocationChanged(Location location){
// Redraw the marker when get location update
drawMarker(location);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
};
if(location!=null){
// Place the initial marker
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
}
private void drawMarker(Location location){
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude()))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME");
}
And if i replace .icon with .setIcon, the whole new MarkerOptions() is in red and I get this error, Cannot invoke title(String) on the primitive type void. What should I do?
You have misplaced a parenthesis when creating your marker, therefore methods icon and title are unrecognized.
Replace your code to:
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
This was pretty obvious as MarkerOptions object doesn't have a setIcon method, but a Marker has one. And adding a MarkerOptions to the map returns a Marker object :-)
Just for clarification, you could set the icon like this:
Marker myMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng" + location.getLongitude())
.title("ME"));
myMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

Categories

Resources