Question

I just want to know why that code gives me a lot of markers at the same place when I try to get users current location ?

I didn't manage to do that in a different class service if anyone knows how to do that in a service or AsyncTask that will help me a lot in my project.

Thanks!

package toutel.testcarte;

import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity {

    private MapController mapController;
    private MapView mapView;
    private GeoPoint myposition;
    private ItemizedOverlay<OverlayItem> mMyLocationOverlay;
    private ResourceProxy mResourceProxy;

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapController = (MapController) mapView.getController();
        GeoPoint myposition = new GeoPoint(48.856614, 2.3522219000000177);
        mapView.setTileSource(TileSourceFactory.MAPNIK);
        mapView.setBuiltInZoomControls(false);
        mapView.setMultiTouchControls(true);
        // mapController.animateTo(myposition);
        mapController.setZoom(13);
        mapController.setCenter(myposition);

        Context context = getApplicationContext();

        CharSequence text = "Activez votre GPS pour utiliser la localisation ";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
         getMenuInflater().inflate(R.menu.main, menu);
         return true;
    }

    public boolean onOptionsItemSelected(MenuItem menu) {

         switch (menu.getItemId()) {

         case (R.id.fermer): {

              System.exit(0);
              break;
         }

         case (R.id.position): {

              LocationManager lm = (LocationManager)    getSystemService(Context.LOCATION_SERVICE);

              while (true) {

                   LocationListener mylocationlistener = new LocationListener() {

                       public void onLocationChanged(Location location) {

                           Context ctx = getApplicationContext();
                           GeoPoint myposition = new GeoPoint(
                                     location.getLatitude(), location.getLongitude());
                           mapController.animateTo(myposition);
                           mapController.setCenter(myposition);
                           mapController.setZoom(17);
                           Marker marker = new Marker(mapView);
                           marker.setPosition(myposition);
                           marker.setAnchor(Marker.ANCHOR_CENTER,
                                            Marker.ANCHOR_BOTTOM);
                                            mapView.getOverlays().add(marker);
                           mapView.invalidate();
                           try {
                               Thread.sleep(10 * 1000);
                           }
                           catch (InterruptedException e) {
                               e.printStackTrace();
                           }

                       }

                       @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
                       }

                   };

                   lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, mylocationlistener);

                   break;
               }
           }

           case (R.id.itineraire): {

           }

        }
        return false;
    }

}
Was it helpful?

Solution

Multiple markers : why?

You are getting multiple markers because every time location is changed you are placing a marker on the map.even change in the position is too small.You are placing marker.Try to zoom in you will see that all markers are not at same position.

My suggestion there is no need of service here.Because OnlocationChanged listener automatically do your job.I have written this single class.Now where ever in the project you need the GPS coordinates, just instantiate the class object and get the Latitude and Longitude.

  LocationSender loc = new LocationSender(YourClass.this);

As i declared lat,lng (in LocationSender.java) as static so i can get any where its values.

  double latitude = LocationSender.lat;
  double longitude = LocationSender.lng;

LocationSender.java

public class LocationSender {
Context context;
LocationManager locationManager;
Location location;
static double lat,lng;
public LocationSender(Context ctx) {
context=ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

// Acquire a reference to the system Location Manager
public void getNewLocation(Location location) throws JSONException 
{
String latLongString = "";
if (location != null) {
    this.location=location;
  lat= location.getLatitude();
   lng = location.getLongitude();
    latLongString = "Lat:" + String.valueOf(LocationActivity.lat) + "\nLong:" +        String.valueOf(LocationActivity.lng);
    Log.d("Location Found", latLongString);
   } else
  {
    location=null;
    latLongString = "No location found";
}
Toast.makeText(context, latLongString, Toast.LENGTH_LONG).show();
 }

 LocationListener locationListener = new LocationListener() {
 public void onLocationChanged(Location location) {
  // Called when a new location is found by the network location provider.
    try {
        getNewLocation(location);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }

   }



   public void onProviderEnabled(String provider) {

    Toast.makeText(context, "Provider: "+provider+" : Enabled", Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String provider) {

    Toast.makeText(context, "Provider: "+provider+" : disabled", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Toast.makeText(context, "Provider: "+provider+" : status: "+status, Toast.LENGTH_LONG).show();

    }
    };    

    }

Also don't forget to add the permissions in AndroidManifest.xml

OTHER TIPS

Do you really need a custom implementation for the location manager / location service's onLocationChanged() callback ?

Otherwise, you could take a look at OSMDroid's MyLocationNewOverlay class https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/mylocation/MyLocationNewOverlay.java?r=1220

There is also another implementation, (deprecated unfortunatelly) called MyLocationOverlay https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/org/osmdroid/views/overlay/MyLocationOverlay.java?r=902

In my implementation, I use it like this:

//declare variable; global - because I need reference elsewhere
private MyLocationOverlay self;

//somewhere in code
//'this' - is the context
//mapMainView - my mapView
self = new MyLocationOverlay(this, mapMainView);
self.enableMyLocation();
self.enableFollowLocation();

//add the overlay to the map and refresh the view
mapMainView.getOverlays().add(COUNT+1, self);//COUNT is the size of the List<Overlay> returned by  mapMainView.getOverlays(); this is just because I want my 'self' to be always the last overlay added
mapMainView.invalidate();//refresh the view

This puts a default icon at my location on the map, and it updates constantly as I move.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top