I am coming with an answer to my question. I don't know if it will work with all people facing the same problem. I just tried to restart the mobile device. After it restarts, it gets the correct current location. So it was a hardware problem though I thought it is something in the code..
Current location in Google-map-API V2
-
16-06-2023 - |
Pergunta
I am using Google API V2 in an Android application. I want to get my current location and add a marker on it. I am using my friend device. when I run the code, it shows me my-friend's house location. I am really shocked why.
could anyone please help me getting my current location..
Solução 3
Outras dicas
Thats because you're first loading the LastKnownLocation, because it's your friends phone it will show your friend last known location (his house).
The code looks fine, I think you have to wait untill it finds the real location.
(make sure you got all permissions, and gps is on)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
When you call locationManager.getLastKnownLocation(provider)
your are retrieving the last location of the GPS that can be like you say when your friend was at home.
If you want to have the location where you are at, you should call requestSingleUpdate
for just one time update or requestLocationUpdates
for a continuous update.
An example for the one time update with a button listener:
btnupdate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}, getMainLooper());
}
});
This implements a listener for the LocationManager, that gives you the posibility to do some actions depending of the Location status.
In your case, you have implemented the listener on the activity, so just try calling:
locationManager.requestSingleUpdate(criteria, this);
This request just single update to show your present location