Search code examples
androidosmdroid

OSMdroid Cannot get current location in android studio


Firstly I am new to OSMdroid. I know there is other similar questions on this topic but there are no recent questions and the answers to the older questions don't work on my code...

I can't get the current location using OSMDroid. I have used the simple tutorial given on github and the suggestions given in previous questions. I have the latest version of OSMDroid but when I try to add a tag for the current location, nothing comes up.

I don't even get errors, the map just displays with no marker for the current location. Help! Here is my code.

Any help would be greatly appreciated as it is very annoying!

Java Class
@Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        Context ctx = getApplicationContext();
        //important! set your user agent to prevent getting banned from the osm servers
        Configuration.getInstance().load(ctx, 
        PreferenceManager.getDefaultSharedPreferences(ctx));
        setContentView(R.layout.activity_map);

        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setTileSource(TileSourceFactory.MAPNIK);

        mMapView.setBuiltInZoomControls(true);
        mMapView.setMultiTouchControls(true);

        IMapController mapController = mMapView.getController();
        mapController.setZoom(9);
        GeoPoint startPoint = new GeoPoint(52.1237453, 6.9293683);
        mapController.setCenter(startPoint);

        this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(ctx),mMapView);
        this.mLocationOverlay.enableMyLocation();
        mMapView.getOverlays().add(this.mLocationOverlay);

XML code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tilesource="Mapnik" />
</LinearLayout>

Solution

  • Two possible reasons.

    1) Your manifest is missing permissions for ACCESS_FINE_LOCATION

    2) If the target SDK is 23 or newer, you have to ask for user level GPS permissions before creating the GpsMyLocationProvider

    There are examples of both in the osmdroid sample application's source code, located here: https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/java/org/osmdroid/intro/PermissionsFragment.java#L94

    and here:

    https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/AndroidManifest.xml#L24