2

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

    }
DurgaPrasad Ganti
  • 1,008
  • 4
  • 20
  • 41
  • as per my opinion remove older locations in `onPause()` like `locationManager.removeUpdates(this);` and request location update in `onResume()` like `locationManager.requestLocationUpdates(provider, 400, 1, this);` – M D Mar 04 '14 at 05:10

3 Answers3

2

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" />
M D
  • 47,665
  • 9
  • 93
  • 114
1

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.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
0

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

Ankit
  • 256
  • 1
  • 9