googleMap.getMyLocation(); cannot get current location - android

i want to make a program to calculate the distance between some places to my current location, but my googleMap.getMyLocation(); doesnt work properly.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setCompassEnabled(false);
mylocation = googleMap.getMyLocation();
direction = new GMapV2Direction();
LatLng from, to;
from = new LatLng(-7.26071409, 112.80674726);
for(int i=0; i<lat.length; i++){
to = new LatLng(lat[i], lon[i]);
doc = direksi.getDocument(from, to, GMapV2Direction.MODE_DRIVING);
distance[i] = (double)direction.getDistanceValue(doc) / 1000;
}
i saved the latitude and longitude of some places in lat[] and lon[].
LatLng 'from' is mylocation and 'to' is my destination places.
the problem appear when i change
from = new LatLng(-7.26071409, 112.80674726);
to
from = new LatLng(mylocation.getLatitude(), mylocation.getLongitude());
i want to do the calculation without opening the googlemaps. the google maps will appear when i touch the map button as pop up window. so the calculation will happen without opening googlemap
please help me

Try this...I hope this will be help to you
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();

This is my code for you, I hope this help you... edit it if you think, it isn't with correct sintaxis...
This work for android 4.x and 5.x and 6.x, I not test this in android 7
//I use this like global var to edit or get informacion about google map
GoogleMap gMap;
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
if (ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Activity_Map.this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
if(!gMap.isMyLocationEnabled())
gMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if(myLocation!=null){
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14), 1500, null);
}
}
}

getMyLocation() => this method is deprecated. You need to use LocationClient instead.
You can find informations about LocationClient and how to get current location here

Related

get current location android

I have a problem with getting current location because, I have in my MainActivity the listener:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
new MyLocationListener()
);
And I have a second activity where I would, when i click on button, calculate distance from my location and gps coordinate that I will pass with distanceTo and return true if the distance is beetween 0 and 200.
So I have a function in SecondActivity
private boolean checkCoordinate(String gps) {
LocationManager lm = (LocationManager) getSystemService(App.getContext().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return false;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
Location loc1 = new Location("");
loc1.setLatitude(currentLatitude);
loc1.setLongitude(currentLongitude);
String[] sep = gps.split(",");
double latitude = Double.parseDouble(sep[0]);
double longitude = Double.parseDouble(sep[1]);
Location loc2 = new Location("");
loc2.setLatitude(latitude);
loc2.setLongitude(longitude);
float distanceInMeters = loc1.distanceTo(loc2);
if(distanceInMeters < 200){
return true;
}else{
return false;
}
}
But the problem is that someTimes and maybe when I don't change my location the function:
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return null, and I don't understand how know my current location because I have already set requestLocationUpdates.
so I how can know my current location?
getLastKnownLocation will return null if GPS based location is disabled in system or there was no GPS fix since system startup. If you want to ensure there is a location you can use the requestSingleUpdate-method, it will not return until there is a location available.
It might also be a good idea to not use the APIs based on specific provider name if it's not important to use a specific provider (usually it is not important how you got the location). The API contains methods that take a Criteria-object instead of a provider name and you can define very precisely what accuracy level etc. you want.

How to update my location when i move and it have to show you are in point 1 radius or not?

i tried this but its showing my current location first time i get information that i am inside or not . but when i moved outside of radius of point 1 its doesn't showing anything.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//drawing marker
LatLng pointOne = new LatLng(23.10,72.50847684);
mMap.addMarker(new MarkerOptions().position(pointOne).title("Point 1"));
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Point 2").snippet("N"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
//myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = myLocation.getLatitude();
Log.e("latitude", String.valueOf(latitude));
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng pointTwo = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(pointTwo)); Log.e("location", String.valueOf(pointTwo));
//drawing overlay circle on marker
Circle circle = mMap.addCircle(new CircleOptions()
.center(pointOne)
.radius(5000)
.strokeColor(0x40FF0000)
.fillColor(0x35FF0000));
//for Checking marker is inside or not
float[] distance = new float[2];
Location.distanceBetween( pointTwo.latitude, pointTwo.longitude,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
pointToPosition(pointOne);
}
Thanks for Help In advance
You can Use Google GeoFencing API to draw a virtual circle of some radius around the location.On user's entry/exit an event will be triggered which will help your cause.
Now getLastKnownLocation() which you are using May or May Not provide a location value. LocationManager maintains GPS location data until that data becomes outdate in like 8mins odd. After this, there will again be a cold startup and the GPS in your phone will try to get a fix and return results.
In case this is a cold startup, you can also get a NullPointerException because of the fact that the your last know location is outdated.
You can try a requestLocationUpdates() .... if lastKnownLocation returns a Null result...
This will cause the LocationManager to explicitly call the GPS in your phone to search for the current location... this will provide results in a callback function onLocationChanged... here you can get the current location....

Best way to get users location in Google Maps Android

I have tried FusedLocationAPI, however, the accuracy it returns is too high as compared to setMyLocationEnabled(true), so the result is as follows, where the Blue circle is plotted by setMyLocationEnabled and the Black one is the accuracy as plotted by FusedLocationAPI.
I also used this piece of code
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
LatLng myPos = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(myPos).title("Start"));
But the marker plotted is again, too far away from he setMyLocationEnabled(true) like this
So I was wondering if there was a better way to get location more accurately?
Try using ACCURACY_FINE instead of ACCURACY_COARSE in your criteria.setAccuracy(Criteria.ACCURACY_COARSE); Hope that helps.

google Maps v2 API for android location return null [duplicate]

This question already has answers here:
My current location always returns null. How can I fix this?
(7 answers)
Closed 7 years ago.
Hi I need some help with this, I have already looked and try many different things. I'm trying to get my current location on android but since the location comes back null my app crashes. I really need help with this please.
I don't know if I'm being clear in here but everytime I call getLastKnownlocation it comes back null, so when I try to get the double lat= location.getLatitude() same for the longitude it won't return anything and there is where my app crashes.
Help...
Here a piece of code
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng latLng = new LatLng(lat, lng);
at latitude is where it stops.
Do you retrieve the GoogleMap object from the fragment before calling those functions?
Something like:
//get map fragment from the static layout (in this case it has id = "map")
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
//get GoogleMap object, then you can start using it, for example enabling the location
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
Thank you all for your help I appreciate it, I have already solved my problem.
Here a piece of code that helped me get ti done:
//I needed to have this line before everything else for me to get my current
//location from getLastKnownLocation method.
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
//And the all the codes I had before
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng latLng = new LatLng(lat, lng);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("Here"));

Android LocationManager.getLastKnownLocation() returns null on Android 4.1.1

I am working on android application. I am stuck in problem.
getLastKnownLocation(provider) returns null for Android version 4.1.1, while for other versions it is fine. Provider is enabled and the rest is ok. I don't know where is the problem. Here is the code.
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.clear();
System.out.println("Current Location = "+latLng);
locationManager.getLastKnownLocation will return null if the provider is disabled, and here is the documentation
http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
try this its working for me...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});

Categories

Resources