Mehdi Haghgoo
Mehdi Haghgoo

Reputation: 3484

Cannot add my location overlay to osmdroid map

I am trying to add my GPS location to the map using the following code:

MyLocationNewOverlay locationOverlay;
locationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(mContext), mapView);
            locationOverlay.enableMyLocation();
            mapView.getOverlays().add(locationOverlay);

However, the code has no effect and adds nothing (e.g. no icons, no text, etc.) to the map. Note that zoom overlay and gesture overlay work perfectly, but the MyLocationNewOverlay overlays have no effect when I add them to the map view. Any ideas?

Update:

This is the code for my activity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
    private static final int STORAGE_REQUEST = 100;
    private static final int LOCATION_REQUEST = 101;
    private static final String TAG = "MainActivity";
    private Context mContext;
    private MapView mMap;
    private EditText latitude;
    private EditText longitude;
    private Button searchLocation;
    IMapController mapController;

    private MyLocationNewOverlay locationOverlay;

    ArrayList<OverlayItem> items = new ArrayList<>();

    /**
     * Compass overlay
     */
    private CompassOverlay mCompassOverlay;


    private RotationGestureOverlay mRotationOverlay;

    private ScaleBarOverlay mScaleBarOverlay;


    private MyLocationNewOverlay mMyLocationOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getApplicationContext();

        Configuration.getInstance().load(mContext, PreferenceManager.getDefaultSharedPreferences(mContext));
        Configuration.getInstance().setUserAgentValue("Dalvik");


        setContentView(R.layout.activity_main);


        //Check Permissions
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_REQUEST);
        }

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST);
        }


        mMap = findViewById(R.id.mapView);
        mMap.setTileSource(TileSourceFactory.MAPNIK);


        mMap.setBuiltInZoomControls(true);
        mMap.setMultiTouchControls(true);


        latitude = findViewById(R.id.latitude);
        longitude = findViewById(R.id.longitude);
        searchLocation = findViewById(R.id.searchLocation);
        searchLocation.setOnClickListener(this);


        mapController = mMap.getController();
        mapController.setZoom(9.0f);

        //Add my location

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);

        final LocationManager locMgr = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        final String provider = locMgr.getBestProvider(criteria, true);
        locMgr.requestLocationUpdates(provider, 1000, 100, this);

        Location loc = locMgr.getLastKnownLocation(provider);
        Log.d(TAG, "onCreate: " + loc.getLatitude() + ", " + loc.getLongitude());

        //Start on Iran
        GeoPoint iran = new GeoPoint(32.4279, 53.6880);
        mapController.setCenter(iran);


        //Add my location overlay
        mMyLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(mContext), mMap);
        mMyLocationOverlay.enableMyLocation();
        mMap.getOverlays().add(mMyLocationOverlay);

        //Add compass overlay
        mCompassOverlay = new CompassOverlay(mContext, mMap);
        mCompassOverlay.enableCompass();
        mCompassOverlay.setEnabled(true);
        mMap.getOverlays().add(mCompassOverlay);



        //Add rotation gesture overlay
        mRotationOverlay = new RotationGestureOverlay(mMap);
        mRotationOverlay.setEnabled(true);
        mMap.setMultiTouchControls(true);
        mMap.getOverlays().add(mRotationOverlay);


        //Add map scale bar overlay
        mScaleBarOverlay = new ScaleBarOverlay(mMap);
        mScaleBarOverlay.setCentred(true);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 30);
        mMap.getOverlays().add(mScaleBarOverlay);



    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        //Check and decide
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(mContext, R.string.permission_not_granted_please_allow, Toast.LENGTH_LONG).show();
        }

    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.searchLocation) {
            double lat = Double.valueOf(latitude.getText().toString());
            double lng = Double.valueOf(longitude.getText().toString());

            GeoPoint geoPoint = new GeoPoint(lat, lng);
            mapController.setCenter(geoPoint);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMyLocationOverlay.setEnabled(false);
        mMap.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMyLocationOverlay.setEnabled(true);
        mMap.onResume();

    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }
}

Upvotes: 3

Views: 3139

Answers (2)

spy
spy

Reputation: 3258

This gets asked a lot. Here's the most common reasons for it not to work

  • Does your device even have GPS?
  • Does your device have GPS service enabled?
  • osmdroid only adds GPS by default, you may need to add the Network Location server to the list of sensors that the overlay queries for
  • Are you outside and have a GPS signal?
  • Do you have permissions granted in the manifest?
  • If targeting API23+, have you asked the user for runtime permissions?

If you happen to have a custom location provider or need to customize what location feeds the overlay uses, try the following

GpsMyLocationProvider prov= new GpsMyLocationProvider(); 
prov.addLocationSource(LocationManager.NETWORK_PROVIDER);
MyLocationNewOverlay locationOverlay = new MyLocationNewOverlay(prov, mapView);
locationOverlay.enableMyLocation();
mMap.getOverlayManager().add(locationOverlay);

then proceed as normal.

Upvotes: 3

Mehdi Haghgoo
Mehdi Haghgoo

Reputation: 3484

It seems that you cannot use GpsMyLocationProvider to add overlay to a map. A better way might be using ItemizedIconOverlay, in which you get location normally from Android using Android's getLocationUpdates, create a GeoPoint, create an ItemOverlay, add it to anItemizedIconOverlay, and then add this to your MapView:

  final LocationManager locMgr = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        final String provider = locMgr.getBestProvider(criteria, true);
        locMgr.requestLocationUpdates(provider, 1000, 100, this);

        Location loc = locMgr.getLastKnownLocation(provider);


        //Add my location overlay
        OverlayItem newItem = new OverlayItem("Here", "You are here", new GeoPoint(loc));
        items.add(newItem);

        ItemizedIconOverlay<OverlayItem> myLocOverlay = new ItemizedIconOverlay<OverlayItem>(items,
                getResources().getDrawable(R.drawable.my_location, null),
                new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
                    @Override
                    public boolean onItemSingleTapUp(int index, OverlayItem item) {
                        return false;
                    }

                    @Override
                    public boolean onItemLongPress(int index, OverlayItem item) {
                        return false;
                    }
                },
        mContext);
        mMap.getOverlays().add(myLocOverlay);

Upvotes: 1

Related Questions