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

    }
Durga
  • 970
  • 4
  • 19
  • 39
  • 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,398
  • 9
  • 92
  • 112
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
  • 28,933
  • 23
  • 88
  • 140
  • then how i will get lat long values – Durga Mar 04 '14 at 05:08
  • @Durga, there is a method named `onLocationChanged(Location location)` This method automatically gets called by system. – Lucifer Mar 04 '14 at 05:10
  • @Durga, you are performing Location operations in onCreate() method, which is not good. I advice you to move it to the `onLocation()` method. This is the right way to do it. – Lucifer Mar 04 '14 at 05:11
  • @Durga, that is going to take a while, Please wait. Can you send me your code to my email mentioned in my profile ? that way, I can do it faster. – Lucifer Mar 04 '14 at 05:16
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48919/discussion-between-kedarnath-and-durga) – Lucifer Mar 04 '14 at 05:22
  • 1
    I think need to first register location listener to get updated location locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); other wise onLocationChanged not called by system. – Ankit Mar 04 '14 at 05:25
  • @Durga, I have sent you code via email, Please check it. – Lucifer Mar 04 '14 at 05:41
  • @Durga ,any progress ? – Lucifer Mar 04 '14 at 06:23
  • sorry Kedarnath for late respond now its working fine – Durga Mar 04 '14 at 06:31
  • thank u very much..now i want to show that address at marker is it possible? – Durga Mar 04 '14 at 06:32
  • @Durga, sure it is possible. use [GeoCoder class](http://developer.android.com/reference/android/location/Geocoder.html) for this. Here is my [answer](http://stackoverflow.com/a/21930761/3330969) for same. – Lucifer Mar 04 '14 at 06:35
  • ya its ok but i want to add this address in map when click on my map point – Durga Mar 04 '14 at 06:41
  • @Durga, That's ok, To display address on map check this [answer1](http://stackoverflow.com/a/19318323/3330969) and [answer2](http://stackoverflow.com/a/6714764/3330969). – Lucifer Mar 04 '14 at 06:49
  • here i have problem when first time zoom out it shows one marker again zoom in and zoom out it show two or more markers what is the problem – Durga Mar 04 '14 at 06:51
  • @Durga I dont think it is a problem, It is actually when you zoom out then you have very large view to display that time, most famous address is get displayed. As you zoom in, it gets more and more details and regoin gets small so you see more markers. – Lucifer Mar 04 '14 at 06:53
  • @Durga, I do not think if you can avoid it. – Lucifer Mar 04 '14 at 06:59
  • @Durga ok try it. Till now I have did only a sample android map project. I do not have experience like you. But I am sure you can do it. – Lucifer Mar 04 '14 at 07:04
  • no no i am not a experience person i am new in android – Durga Mar 04 '14 at 07:05
  • @Durga, same here, Nice to meet you :). I am happy that my efforts worked for you. – Lucifer Mar 04 '14 at 07:06
  • but you supported well for me – Durga Mar 04 '14 at 07:06
  • i will search for that..if you found any thing please share me – Durga Mar 04 '14 at 07:08
  • @Durga sure for that. – Lucifer Mar 04 '14 at 07:10
  • @Durga, Here you go [Google Map](http://www.androidhive.info/2013/08/android-working-with-google-maps-v2/). This is the best tutorial I have found. It demonstrate all the things of Map. – Lucifer Mar 04 '14 at 08:27
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