I'm tring to get the location from the gps/netwrok by best provider but always it's return the same location, also i can see that on google map there is a sign to my right location.
please anyone can tell me what i'm doing wrong?
My activity is:
public class MainMenu2 extends Activity implements LocationListener, OnClickListener
on my onCreate i have:
if(isGooglePlay()){
setContentView(R.layout.menu_2);
setUpMapIfNeeded();
}
isGooglePlay method:
private boolean isGooglePlay() { // looks if googlemaps is available
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(status == ConnectionResult.SUCCESS){
return true;
}
else{
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
//Toast.makeText(this, "Google Play is not available", Toast.LENGTH_SHORT).show();
return(false);
}
}//isGooglePlay
setUpMapIfNeeded method:
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.menu_map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
mMap.setMyLocationEnabled(true);
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, true);
if (provider == null){
onProviderDisabled(provider);
}
locationManager.requestLocationUpdates(provider, 100, 1, this);
loc = locationManager.getLastKnownLocation(provider);
//---here the privider is "gps" but always the same location---//
if (loc != null){
onLocationChanged(loc);
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // set Map Type
}
}
}//setUpMap
and override methods:
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
double pLong = location.getLongitude();
double pLat = location.getLatitude();
Latstr = String.valueOf(pLong);
Lngstr = String.valueOf(pLat);
latitude = pLat;
longitude = pLong;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Please turn ON the GPS", Toast.LENGTH_SHORT).show();
}
#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
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
myLatLng = new LatLng(latitude,longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(myLatLng, 15);
mMap.animateCamera(update);
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude )).title("Find me here!"));
}
i also tried to search here for similer problem but i didn't got nothing..
There is a bug with LocationProvider on some platforms like Samsung, custom Android build. You need to call this code (which actually does nothing), which triggers the phone's background cache to update its current location.
If you dont believe me, change your Gps position to a different location about 200m away, load your app, you dont notice the location gps change. Now, just load Maps app on your phone and suddenly your app will show current location.
To do this trigger programmatically put these lines just before your getLastKnownLocation call.
HomeScreen.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
Edit
OR
Use the new api's LocationClient instead of LocationProvider.
Related
I am facing a problem, I am trying to show current location on map. When I use wifi, it works fine, but when I turn the GPS on, it stops showing it, again I turn off GPS it works.. what shall I do, I need to show my location as well as the GPS.
my code is:
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_test);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.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 From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
System.out.println("STREEEETTT111: "+db.getIdn(arg0.getTitle()));
Intent i=new Intent(MapTest.this,PharmacyDetails.class);
i.putExtra("name", arg0.getTitle());
startActivity(i);
}
});
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#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
}
and I want to attach the screenshots to make my question more clear:
When the GPS is off:
And when the GPS is on:
Please help, thankx
I am new in android developing, and so intrested in getting location of users!!!!!
You may know that we can access users location by two types:
GPS (ACCESS_FINE_LOCATON)
Network based (ACCESS_COARSE_LOCATION)
My Question is:
I Want to get the location(latittude & longitude) of user by GPS. But, if the user has turned GPS Off/GPS isn't supported, then i want to get user's location by Network, or, Network-based location
.
Hope you understood my question....
Any help is accepted
Try the following code:
LocationManager mlocManager;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
//if condition to check if GPS is available
if (mlocManager .isProviderEnabled(LocationManager.GPS_PROVIDER)) { mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
mlocListener, null);
}
else if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestSingleUpdate(
LocationManager.NETWORK_PROVIDER, mlocListener, null);
}
//this is the class to get the location.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
//you may store these values where ever required.
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
When you use the FusedLocationProviderApi as used in the getting the last known location training and receiving location updates training, it will automatically fall back to network location if GPS is not available.
Hope get GPS code helps you.
if (Common.getIsGPSEnabled()) {
final LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener;
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
myLocation = locationManager.getLastKnownLocation(locationProvider);
Toast.makeText(c, "location changed, My location is removed to"
+ myLocation.getLatitude()+","+myLocation.getLongitude(), Toast.LENGTH_LONG).show();
Latitude = myLocation.getLatitude();
Longitude = myLocation.getLongitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(locationProvider, (long)0, (float)0, locationListener);
myLocation = locationManager.getLastKnownLocation(locationProvider);
if(myLocation != null)
{
///
}
}
i am trying to get location from both network provider and gps.By using the returned latitude and longitude i am placing markers on map. When i tried with network provider app is working fine.But when i tried to get location from gps, for the first time it is returning null. After that it is giving me exact location result. How to get rid from this.?
I think some minor changes i have to made, please suggest me in fixing this.
this is how i am doing this.
public class MapActivity extends Activity implements LocationListener {
private GoogleMap gMap;
private LocationManager locationManager;
private String provider;
boolean gps_enabled = false;
boolean netwrk_enabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
//Focussing india on starting map
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
23.40276491, 77.51953125), 5));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
netwrk_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled)
provider = LocationManager.GPS_PROVIDER;
else
provider = LocationManager.NETWORK_PROVIDER;
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
CameraPosition cp = new CameraPosition(new LatLng(
location.getLatitude(), location.getLongitude()), 14, 40, 90);
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 4000,
null);
gMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude()))
.title("I am here"));
if (location != null) {
if (provider == LocationManager.GPS_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from gps",
Toast.LENGTH_SHORT).show();
else if (provider == LocationManager.NETWORK_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from network",
Toast.LENGTH_SHORT).show();
new HttpGetTask().execute();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub18d1:d002
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
//Passing latitude and longitude here to get lat longs from my remote server.
// using json parsing i am placing multiple markers here.
}
}
Everything you code is write, But you are not calling LocationManager on starting of Application. Just un comment the following line from your code from your onCreate() method.
//Location location = locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
Uncomment above line and make following change for provider
Location location = locationManager.requestLocationUpdates(provider, 5000L, 10F, this);
i am developing one application in that i want to show my current location in the map,it shows but if i change location its shows previous location please tell me in my code mistake
my code
public class GetLatLongForTPActivity extends FragmentActivity implements LocationListener{
GoogleMap _googleMap;
static final LatLng SEC = new LatLng(17.433189,78.502223);
static final LatLng Safilguda = new LatLng(17.464166,78.536156);
static final LatLng Fathe = new LatLng(17.455932,78.450132);
LatLng myPosition;
LatLongDetails latLongDetails = new LatLongDetails();;
private EditText timeEdit;
private Button submitBtn;
private Button cancelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
/*Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
*/
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
Log.e(" NEW LATLONG1",arl.get(0).toString());
Log.e(" NEW LATLONG2",arl.get(1).toString());
Log.e(" NEW LATLONG3",arl.get(2).toString());
_googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
if(_googleMap==null){
Toast.makeText(getApplicationContext(), "Google Map Not Available", Toast.LENGTH_LONG).show();
}
LocationManager locationManger = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
Marker perth = _googleMap.addMarker(new MarkerOptions()
.position(SEC)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
/*Marker Safilg = _googleMap.addMarker(new MarkerOptions()
.position(Safilguda)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
Marker Saf = _googleMap.addMarker(new MarkerOptions()
.position(Fathe)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));*/
String provider = locationManger.getBestProvider(criteria, true);
Location location = locationManger.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
latLongDetails.setLat(latitude);
latLongDetails.setLongi(langitude);
Log.e("lat",""+ latLongDetails.getLat());
Log.e("long", ""+latLongDetails.getLongi());
LatLng latlang = new LatLng(latitude, langitude);
LatLngBounds curScreen = _googleMap.getProjection().getVisibleRegion().latLngBounds;
curScreen.contains(latlang);
myPosition = new LatLng(latitude, langitude);
_googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
_googleMap.addMarker(new MarkerOptions().position(myPosition).title("start"));
//_googleMap.setOnMarkerClickListener(GetLatLongForTPActivity.this);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String
clreatime=timeEdit.getText().toString().trim();
latLongDetails.setClearTime(clreatime);
Log.e("time",
latLongDetails.getClearTime());
new
SendLatLongValAsync(GetLatLongForTPActivity.this).execute(latLongDetails);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
Setup your Activity like below:
public class BasicMapActivity_new extends FragmentActivity implements LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private String provider;
Double Latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
mMap.setMyLocationEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
} else {
//do something
}
setUpMap();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
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.map2))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
Marker startPerc=null;
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng)
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f))
}
#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
}
}
And do not forget to add permission into manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You have used getLastKnownLocation() method while fetching the location details. This method always returns the last know co-ordinates. So, I suggest you to commenting this line Location location = locationManger.getLastKnownLocation(provider); from your code. Then it will run properly.
To update your location you have to register your Location Listener to location manager. And use override method onLocationChanged() to get latest location.
Please refer http://developer.android.com/guide/topics/location/strategies.html
This Google Maps v2 api confuses me quite a bit. I have implemented it now in some way i would like to use it. I just have two small problems that i don't know how to go about.
Sometimes I don't get a location when i start the app with gps enabled or it takes way too long to get one.
So I would like it to always load with the internet location provider first to have a very fast location fix as well as always using the getlastknownlocation() first. Cant figure out how to go about it.
Here my code:
public class MapViewMain extends FragmentActivity implements LocationListener, LocationSource
{
private GoogleMap mMap;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
final int RQS_GooglePlayServices = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mapviewmain);
//start power button service
Intent intent=new Intent("com.epicelements.spotnsave.START_SERVICE");
this.startService(intent);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
Toast.makeText(this, "Google Service not found", Toast.LENGTH_LONG).show();
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locationManager != null)
{
boolean gpsIsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean networkIsEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsIsEnabled) {
// Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
PopIt("No GPS found", "Would you like to go to the settings to activate it?");
}
if(gpsIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
}
else if(networkIsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000L, 10F, this);
}
else
{
//Show an error dialog that GPS is disabled...
}
}
else
{
//Show some generic error dialog because something must have gone wrong with location manager.
}
setUpMapIfNeeded();
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
locationManager.getBestProvider(criteria, true);
if(mListener != null){
}
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Enable the my-location layer
if(locationManager != null)
{
mMap.setMyLocationEnabled(true); // Enable the my-location layer
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
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();
}
//This is how you register the LocationSource
mMap.setLocationSource(this);
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setPadding(0,60,0,150);
Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE);
}
#Override
public void activate(OnLocationChangedListener listener)
{
mListener = listener;
}
#Override
public void deactivate()
{
mListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( mListener != null )
{
mListener.onLocationChanged( location );
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
//save coordinate
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
editor.putFloat("lat", (float) location.getLatitude());
editor.putFloat("lng", (float) location.getLongitude());
editor.putFloat("accuracy", (float) location.getAccuracy());
editor.commit();
//marker stuff
mMap.clear();
mMap.addMarker(new MarkerOptions()
.position(coordinate)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 16));
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
// Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
// Alarm Dialog if GPS not enabled
public void PopIt( String title, String message ){
new AlertDialog.Builder(this)
.setTitle( title )
.setMessage( message )
.setCancelable(false)
.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of YES
//AlertDialog.dismiss();
}
})
.setNegativeButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//do stuff onclick of CANCEL
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
}
}
You can use LocationClient for your purpose its give LastLocation very fast.
first declare class variable
private LocationClient client;
after in onCreate
try {
if (map == null) {
MapsInitializer.initialize(this);
client = new LocationClient(this, new ConnectionCallbacks() {
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
// TODO Auto-generated method stub
Toast.makeText(MotoFreightHomeMapMainActivity.this,
"onConnected", Toast.LENGTH_LONG).show();
Location currentLocation = client.getLastLocation();
if (currentLocation != null) {
//do you stuff here
}
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
});
client.connect();
}
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
etMap.setVisibility(View.INVISIBLE);
btnEditLocation.setVisibility(View.INVISIBLE);
Toast.makeText(this, "Please install Google Play Library",
Toast.LENGTH_SHORT).show();
}
see full code here
http://developer.android.com/training/location/retrieve-current.html
You can find a sample and tutorial from here.