Moving marker to user location in Android studio - java

I was trying to make a map activity app which when run, displays user's GPS' location on a map using a marker. However, on running, it just displays the marker in the default location (Sydney) please help. Below is my code.. I have tried a number of ways but all of them still lead me to Sydney. What Im trying to do is for the app to take me directly to my location once run.
Below is my code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_location);
// 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);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("My Current Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME, MIN_UPDATES_DISTANCE, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
}

Use LocationCallback instead to get your latest location:
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i(TAG, "Location " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Create instance for current user lat and lng
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add user position marker
currentUserPositionMarker(latLng);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
}
};
/**
* Add Marker for user current position
*
* #param latLng current lat and lng of user
*/
private void currentUserPositionMarker(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(CURRENT_POSITION);
mCurrLocationMarker = gMap.addMarker(markerOptions);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
#Override
public void onPause() {
super.onPause();
if (mFusedLocationProviderClient != null) {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.getUiSettings().setMapToolbarEnabled(false);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES); // 3 seconds interval
mLocationRequest.setFastestInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (isFineLocationPermissionGranted())
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}

You need to get the last known location of the device, use this link to get the last known location, and then display the marker where you want.

Related

How to stop a google map from continuously re-Centering at my location

My problem is related to Google Maps in android. when moving the camera at any point, it returns to my original location instantly, How can I stop that? , You can find my code below
The map starts normally and then for some reason it relocates it self to my original location when i try to navigate the map.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener {
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);
Location lastKnownLocation = locationmanager.getLastKnownLocation(locationmanager.GPS_PROVIDER);
centerMpOnLocation(lastKnownLocation, "your Location ");
}
}
}
public void centerMpOnLocation (Location location, String title){
if (location != null){
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
if (title != "your Location") {
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}else {
Toast.makeText(this, "Wait till we get your Location", Toast.LENGTH_SHORT).show();
}
}
#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);
}
/**
* 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;
mMap.setOnMapLongClickListener(this);
Intent intent= getIntent();
if (intent.getIntExtra("placeNumber", 0) == 0){
locationmanager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationlistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMpOnLocation(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 (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){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
locationmanager.requestLocationUpdates(locationmanager.GPS_PROVIDER, 0, 0, locationlistener);
Location lastKnownLocation = locationmanager.getLastKnownLocation(locationmanager.GPS_PROVIDER);
centerMpOnLocation(lastKnownLocation, "your Location");
}
}
}else {
Location placeLocation = new Location(locationmanager.GPS_PROVIDER);
placeLocation.setLatitude(MainActivity.locations.get(intent.getIntExtra("placeNumber", 0)).latitude);
placeLocation.setLongitude(MainActivity.locations.get(intent.getIntExtra("placeNumber", 0)).longitude);
centerMpOnLocation(placeLocation, MainActivity.memorablePlaces.get(intent.getIntExtra("placeNumber", 0)));
}
}
#Override
public void onMapLongClick(LatLng latLng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address = "" ;
try {
List <Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses != null && addresses.size() > 0){
if (addresses.get(0).getThoroughfare() != null){
if (addresses.get(0).getSubThoroughfare() != null){
address += addresses.get(0).getSubThoroughfare() + " ";
}
address += addresses.get(0).getThoroughfare();
}
}else if( address == "") { // عشان لو ماعرفتش اطلع عنوان هاحتاج اطلع تاريخ ووقت حاجه بديله يعنى
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");
address = sdf.format(new Date());
}
} catch (IOException e) {
e.printStackTrace();
}
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
MainActivity.memorablePlaces.add(address);
MainActivity.locations.add(latLng);
MainActivity.arrayAdapter.notifyDataSetChanged();
Toast.makeText(this, "Location Saved", Toast.LENGTH_SHORT).show();
}
}`
Anyone can fix this.
Thanks
You are centering to your location, each time there is a location update.
locationlistener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
centerMpOnLocation(location, "your Location");
}
...
}
Remove centerMpOnLocation(location, "your Location"); or change your logic.

Cant move in google maps activity. It always return to my current location

I'm working on app which include google maps activity.
My problem is:
When I'm trying to move around in the map or zoom in & out it immediately return to my current location. Also when I search for location, new marker added at the searched location but immediately goes back to my current location.
I searched for solution but found nothing..
I hope somebody can figure it out
This is my google maps activity:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
public LocationManager locationManager;
public LocationListener locationListener;
public DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private ArrayList<User> userArrayList = new ArrayList<>();
User useri;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
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_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker1)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 11));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
mMap.setMyLocationEnabled(true);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
//mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(this, R.raw.style);
//mMap.setMapStyle(style);
mMap.setMyLocationEnabled(true);
final Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
final LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lat").setValue(lastKnownLocation.getLatitude());
mDatabase.child("Users").child(mAuth.getCurrentUser().getUid()).child("lng").setValue(lastKnownLocation.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("המיקום שלי")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker1)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 11));
showUsersOnMap();
}
}
}
// Search for location and show it on the map
public void onClick(View view) {
if(view.getId() == R.id.searchLocationBtn){
EditText searchBoxLocation = (EditText) findViewById(R.id.searchBoxLocation);
String location = searchBoxLocation.getText().toString();
List<Address> addressList = null;
MarkerOptions markerOptions = new MarkerOptions();
if( ! location.equals("")){
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0 ; i < addressList.size(); i++){
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.clear();
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
}
}
}
// Function to show all the users on the map
public void showUsersOnMap(){
mDatabase.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
User user = ds.getValue(User.class);
userArrayList.add(user);
}
for (int i = 0; i < userArrayList.size(); i++) {
useri = userArrayList.get(i);
if (useri.getLat() != 0 && useri.getLng() != 0) {
MarkerOptions markerOptions = new MarkerOptions();
LatLng userlatLng = new LatLng(useri.getLat(), useri.getLng());
markerOptions.position(userlatLng);
mMap.addMarker(new MarkerOptions().position(userlatLng).title(useri.getName()).snippet(useri.getPhone())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_marker2)));
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2,10));
}
else Toast.makeText(getApplicationContext(),"ישנה בעיה. אנא נסה להתחבר למפה שוב",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
UPDATE:
I think I found what was the problem.
I just disabled the mMap.moveCamera() inside onLocationChanged() and it works just fine.
Now Im wondering if its ok to do so? its still keep the camera on my current location when I Drive for example?
In your search code you are adding marker every time in the loop
for (int i = 0 ; i < addressList.size(); i++){
Address myAddress = addressList.get(i);
LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
markerOptions.position(latLng);
mMap.clear();
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
In the same code, you are moving the camera to a specific location mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11))
mMap.addMarker() will add a new marker to map.
mMap.moveCamera() will move the focus to the given location.
Check with your implementation.
Hope it helps:)

Android Location Manager returning null location data

I have very interesting problem,
My Location manager sometimes working, sometimes returning null data.
I check all permission , gradle files options and runtime check about location is enabled. My phone not have airplane mode and I do not off location.
Whatever I check all data, There is no trouble for the get the location data.
Main Code
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);
cs = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("verigeldi");
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return; // check permission
}
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,1000, mLocationListener);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try { // THIS AREA VERY IMPORTANT !!!!
longitude = location.getLongitude(); // GET NULL POINTER EXCEPTION SOMETIMES WORKING
latitude = location.getLatitude(); // GET NULL POINTER EXCEPTION SOME TIMES WORKING
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 13);
mMap.animateCamera(cameraUpdate);
}
catch (Exception e) {
LatLng latLng = new LatLng(39.052540, 35.410083);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 5);
mMap.animateCamera(cameraUpdate);
}
checkLocationIsEnabled();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
}
public final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 13);
mMap.animateCamera(cameraUpdate);
mLocationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};

Current location shows on emulator but not on phone

I am setting up my map to track my location. Right at the start I want it to detect my Lat and Long and show where I am and update the marker location when I move.
When I test this on GenyMotion emulator and input my own positions, it works and shows updated location accordingly. But when I test it on a mobile device, I do not get any marker and get the "Location null" Toast message.
Since it is the first time on the device, there is probably no last known location. Thus wanting to make sure, I took the device and moved a distance (probably 50 meters or so back n forth) and still nothing updated on the device.
public class TrackMapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
Location location;
String provider;
Double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_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);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
try {
//Get last known user location
location = locationManager.getLastKnownLocation(provider);
if(location != null){
Toast.makeText(TrackMapsActivity.this, "Location NOT null", Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
else {
Toast.makeText(TrackMapsActivity.this, "Location null", Toast.LENGTH_SHORT).show();
}
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
protected void onResume() {
super.onResume();
try {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
locationManager.removeUpdates(this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(TrackMapsActivity.this, "You Moved", Toast.LENGTH_SHORT).show();
lat = location.getLatitude();
lng = location.getLongitude();
LatLng yourLocation = new LatLng(lat, lng);
if(mMap != null) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 10));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
do you put the permission for using the gps :)
The main permissions you need are
android.permission.ACCESS_COARSE_LOCATION or
android.permission.ACCESS_FINE_LOCATION.

Can't get coordinates using LocationManager

I'm developing an app that uses the Google Maps V2 API and I'm having trouble do get my coordinates and to put it into the LatLng object... Here's my code:
public class TelaMapa extends android.support.v4.app.FragmentActivity
implements OnMapClickListener, OnCameraChangeListener{
// Google Map
protected GoogleMap googleMap;
private SupportMapFragment mapFragment;
protected AndroidLocationSource locationSource;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_mapa);
}
#Override
protected void onResume(){
super.onResume();
configureMap();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void configureMap() {
if (googleMap == null) {
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googleMap = mapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
LocationManager LM = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String bestProvider = LM.getBestProvider(new Criteria(),true);
Location localAtu;
/*Location myLocation = LM.getLastKnownLocation(bestProvider);
double lat= myLocation.getLatitude();
double lng = myLocation.getLongitude();
LatLng latLng = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));*/
if(bestProvider != null){
localAtu = LM.getLastKnownLocation(bestProvider);
} else {
localAtu = LM.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
LatLng latLng;
if(localAtu != null){
latLng = new LatLng(localAtu.getLatitude(), localAtu.getLongitude());
final CameraPosition position = new CameraPosition.Builder()
.target(latLng)
.bearing(0)
.tilt(0)
.zoom(17)
.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
googleMap.moveCamera(update);
adicionarMarcador(googleMap, latLng);
locationSource = new AndroidLocationSource();
googleMap.setLocationSource(locationSource);
locationSource.setLocation(latLng);
} else {
Toast.makeText(getApplicationContext(),
"GPS desligado ou indisponível!", Toast.LENGTH_LONG)
.show();
}
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Desculpe! Não foi possível criar o mapa!", Toast.LENGTH_SHORT)
.show();
}
}
}
That's it, I installed it in my Motorola Atrix and it always show me the toast in the else
block... Thanks for reading!
Answered by Sanket Kachhela!
Just use this tutorial and it will work fine!
androidhive.info/2012/07/android-gps-location-manager-tutorial

Categories