Reputation: 33
I'm completely new in Android studio and I want to build a project which shows the x,y coordinates of a user in the openstreet map (as a pointer). I viewed the GitHub codes, but it really was a struggle..
I added the map, can you please explain me how can I get my location from gps? Here's my code..
package mytestapplication.hello.com.map;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.mylocation.IMyLocationConsumer;
import org.osmdroid.views.overlay.mylocation.IMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
public class MainActivity extends AppCompatActivity {
MapView map = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
map = findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
IMapController mapController = map.getController();
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
mapController.setZoom((long) 14);
GeoPoint startPoint = new GeoPoint(x, y);
mapController.animateTo(startPoint);
}
@Override
protected void onPause() {
super.onPause();
map.onPause();
}
@Override
protected void onResume() {
super.onResume();
map.onResume();
}
}
Any answer would be completely helpful...
Upvotes: 0
Views: 7690
Reputation: 41
If found this code and it gave me results immediately:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Location lastKnownLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLoc != null) {
int longitude = (int) (lastKnownLoc.getLongitude() * 1000000);
int latitude = (int) (lastKnownLoc.getLatitude() * 1000000);
GeoPoint location = new GeoPoint(latitude, longitude);
}
Problem with myLocationNewOverlay.getMyLocation
: it waits to begin with the locations calculation until other processes are finished (at least for me it seemed like that).
Upvotes: 2
Reputation: 21469
See the osmdroid wiki. The simplest solution is to add a My Location overlay to your map view:
this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(context),mMapView);
this.mLocationOverlay.enableMyLocation();
mMapView.getOverlays().add(this.mLocationOverlay);
Upvotes: 5