Cannot add my location overlay to osmdroid map - android

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) {
}
}

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.

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);

Related

Attempt to invoke interface method 'void org.osmdroid.api.IMapController.animateTo(org.osmdroid.api.IGeoPoint)'

I just finished working on the map using osm but I have an error like this
I have searched for a solution on the internet but I did not find it
this is the code for setupMap
// setting tile map
BingMapTileSource.setBingKey(getString(R.string.bingkey));
BingMapTileSource bingMap = new BingMapTileSource(null);
bingMap.setStyle(BingMapTileSource.IMAGERYSET_ROAD);
// menambah overlay ke dalam map
mapView.getOverlays().add(rotationGestureOverlay);
mapView.getOverlays().add(compassOverlay);
mapView.getOverlays().add(myLocationNewOverlay);
mapView.getOverlays().add(roadNodeMarkers);
//setting mapView
mapView.setTileSource(bingMap);
mapView.setTilesScaledToDpi(true);
mapView.setMinZoomLevel(1.0);
mapView.setMaxZoomLevel(21.0);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(true);
mapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.NEVER);
mapController.animateTo(new GeoPoint(-5.402213, 105.264093));
}
and i got error like this
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void org.osmdroid.api.IMapController.animateTo(org.osmdroid.api.IGeoPoint)' on a null object reference
at com.example.donordarahanjeng.directmap.setupMap(directmap.java:449)
at com.example.donordarahanjeng.directmap.onCreate(directmap.java:150)
when i click error he will head to mapController.animateTo(new GeoPoint(-5.402213, 105.264093));
and this is my full code
public class directmap extends AppCompatActivity implements MapboxMap.OnMapClickListener
, PermissionsListener, View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback
, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
//, MapboxMap.OnMapClickListener, PermissionsListener, View.OnClickListener {
#BindView(R.id.mapViewosm)
MapView mapView;
#BindView(R.id.route)
FloatingActionButton route;
//private MapView mapView;
private MapboxMap mapboxMap;
private FusedLocationProviderClient locationProviderClient;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
// variables for calculating and drawing a route
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
private RoadManager roadManager;
private MyLocationNewOverlay myLocationNewOverlay;
private LocationManager manager;
private IMapController mapController;
private RotationGestureOverlay rotationGestureOverlay;
private GpsMyLocationProvider myLocationProvider;
private CompassOverlay compassOverlay;
protected FolderOverlay roadNodeMarkers;
//private MyLocationNewOverlay myLocationNewOverlay;
private GeoPoint startPoint, destPoint;
private Bitmap startIcon;
// private LocationHelper locationHelper;
private Location location;
private double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context));
//Mapbox.getInstance(directmap.this, getString(R.string.access_token));
setContentView(R.layout.activity_directmap);
ButterKnife.bind(this);
// mapView = (MapView) findViewById (R.id.mapViewosm);
// button = (Button) findViewById(R.id.startButton);
roadManager = new GraphHopperRoadManager(getString(R.string.apikey), true);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
route.setOnClickListener(this);
//mapView.onCre(savedInstanceState);
//mapView.getMapAsync(this);
startIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_mark);
//ambil lokasi pendonatur
lat = -5.402213; //getIntent().getDoubleExtra("latitude", 0);,
lng = 105.264113;//getIntent().getDoubleExtra("longitude", 0);
setupMap();
setupOverlay();
addMarker();
}
private void addMarker() {
Marker destMarker = new Marker(mapView);
destPoint = new GeoPoint(lat, lng);
destMarker.setPosition(destPoint);
destMarker.setTitle(getIntent().getStringExtra("title"));
destMarker.setSubDescription(getIntent().getStringExtra("username"));
destMarker.setIcon(getDrawable(R.drawable.ic_mark));
mapView.getOverlays().add(destMarker);
mapView.invalidate();
}
#Override
protected void onStop() {
super.onStop();
//mapView.onStop();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
//mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
// mapView.onLowMemory();
}
#Override
public void onClick(View v) {
/* if (v == button) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(directmap.this, options);
startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
GeoPoint destination = destPoint;
ArrayList<GeoPoint> waypoints = new ArrayList<>();
waypoints.add(startPoint);
waypoints.add(destination);
// algoritma astar
roadManager.addRequestOption("algorithm=astarbi");
Road road = roadManager.getRoad(waypoints);
} */
if (v.getId() == R.id.route) {
getRoute2();
}
}
#SuppressLint("MissingPermission")
private void getRoute2() {
startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
GeoPoint destination = destPoint;
ArrayList<GeoPoint> waypoints = new ArrayList<>();
waypoints.add(startPoint);
waypoints.add(destination);
// algoritma astar
roadManager.addRequestOption("algorithm=astarbi");
Road road = roadManager.getRoad(waypoints);
// build rute overlay
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
//mengatur warna dan lebar rute
roadOverlay.setColor(Color.BLUE);
roadOverlay.setWidth(7);
putRoadNodes(road);
mapView.getOverlays().add(roadOverlay);
mapView.invalidate();
}
private void setupOverlay() {
//setting map controller
mapController = mapView.getController();
mapController.setZoom(13.0);
//setting node marker
roadNodeMarkers = new FolderOverlay();
roadNodeMarkers.setName("Route Steps");
// setting compass
compassOverlay = new CompassOverlay(directmap.this
, new InternalCompassOrientationProvider(directmap.this), mapView);
compassOverlay.enableCompass();
compassOverlay.setPointerMode(true);
//setting provider lokasi
myLocationProvider = new GpsMyLocationProvider(this.getBaseContext());
myLocationProvider.setLocationUpdateMinTime(1000);
myLocationProvider.setLocationUpdateMinDistance(50);
//setting gesture rotasi
rotationGestureOverlay = new RotationGestureOverlay(mapView);
rotationGestureOverlay.setEnabled(true);
//setting location overlay
myLocationNewOverlay = new MyLocationNewOverlay(myLocationProvider, mapView);
myLocationNewOverlay.enableMyLocation();
myLocationNewOverlay.enableFollowLocation();
myLocationNewOverlay.setPersonIcon(startIcon);
}
private void setupMap() {
// setting tile map
BingMapTileSource.setBingKey(getString(R.string.bingkey));
BingMapTileSource bingMap = new BingMapTileSource(null);
bingMap.setStyle(BingMapTileSource.IMAGERYSET_ROAD);
// menambah overlay ke dalam map
mapView.getOverlays().add(rotationGestureOverlay);
mapView.getOverlays().add(compassOverlay);
mapView.getOverlays().add(myLocationNewOverlay);
mapView.getOverlays().add(roadNodeMarkers);
//setting mapView
mapView.setTileSource(bingMap);
mapView.setTilesScaledToDpi(true);
mapView.setMinZoomLevel(1.0);
mapView.setMaxZoomLevel(21.0);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(true);
mapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.NEVER);
mapController.animateTo(new GeoPoint(-5.402213, 105.264093));
}
private void putRoadNodes(Road road) {
roadNodeMarkers.getItems().clear();
Drawable nodeIcon = getResources().getDrawable(R.drawable.ic_mark); //marker node
int n = road.mNodes.size();
MarkerInfoWindow infoWindow = new MarkerInfoWindow(R.layout.bonuspack_bubble, mapView);
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction);
//ambil titik node
for (int i = 0; i < n; i++) {
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions == null ? "" : node.mInstructions);
Marker nodeMarker = new Marker(mapView);
nodeMarker.setTitle("Step " + (i + 1));
nodeMarker.setSnippet(instructions);
nodeMarker.setSubDescription(Road.getLengthDurationText(this, node.mLength, node.mDuration));
nodeMarker.setPosition(node.mLocation);
nodeMarker.setIcon(nodeIcon);
nodeMarker.setInfoWindow(infoWindow);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty); //icempty
if (iconId != R.drawable.ic_empty) //icempty
{
Drawable image = ResourcesCompat.getDrawable(getResources(), iconId, null);
nodeMarker.setImage(image);
}
nodeMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER);
roadNodeMarkers.add(nodeMarker);
}
iconIds.recycle();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
What should I do? thank you
Your order of initialization is wrong. mapController isn't initialized yet.
mapController gets initialized in setupOverlay():
private void setupOverlay() {
//setting map controller
mapController = mapView.getController();
You are calling mapController.animateTo() from within setupMap(). However setupMap() is called before setupOverlay():
protected void onCreate(Bundle savedInstanceState) {
[...]
setupMap();
setupOverlay();
Either call setupOverlay() before setupMap() or initialize mapController at an earlier step.

I've got an exception at this point

here is my Updated code for real time location activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private Marker currentLocationMaker;
private LatLng currentLocationLatLong;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
startGettingLocations();
mDatabase = FirebaseDatabase.getInstance().getReference();
getMarkers();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng recife = new LatLng(-8.065638, -34.891130);
mMap.addMarker(new MarkerOptions().position(recife).title("Related Searches"));
CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(recife).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onLocationChanged(Location location) {
if (currentLocationMaker != null) {
currentLocationMaker.remove();
}
//Add marker
currentLocationLatLong = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocationLatLong);
markerOptions.title("My Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationMaker = mMap.addMarker(markerOptions);
//Move to new location
CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(currentLocationLatLong).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LocationData locationData = new LocationData(location.getLatitude(), location.getLongitude());
mDatabase.child("location").child(String.valueOf(new Date().getTime())).setValue(locationData);
Toast.makeText(this, "Updated Location", Toast.LENGTH_SHORT).show();
getMarkers();
}
private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList result = new ArrayList();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canAskPermission()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
private boolean canAskPermission() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS disabled!");
alertDialog.setMessage("Enable GPS?");
alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Not", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void startGettingLocations() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean canGetLocation = true;
int ALL_PERMISSIONS_RESULT = 101;
long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;// Distance in meters
long MIN_TIME_BW_UPDATES = 1000 * 10;// Time in milliseconds
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsToRequest;
permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//Check if GPS and Network are on, if not asks the user to turn on
if (!isGPS && !isNetwork) {
showSettingsAlert();
} else {
// check permissions
// check permissions for later versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0) {
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
ALL_PERMISSIONS_RESULT);
canGetLocation = false;
}
}
}
//Checks if FINE LOCATION and COARSE Location were granted
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
return;
}
//Starts requesting location updates
if (canGetLocation) {
if (isGPS) {
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} else if (isNetwork) {
// from Network Provider
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
} else {
Toast.makeText(this, "Unable to get location", Toast.LENGTH_SHORT).show();
}
}
private void getMarkers(){
mDatabase.child("location").addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
if (dataSnapshot.getValue() != null)
getAllLocations((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
}
private void getAllLocations(Map<String,Object> locations) {
for (Map.Entry<String, Object> entry : locations.entrySet()){
Date newDate = new Date(Long.valueOf(entry.getKey()));
Map singleLocation = (Map) entry.getValue();
LatLng latLng = new LatLng((double) singleLocation.get("latitude"), (double) singleLocation.get("longitude"));
addGreenMarker(newDate, latLng);
}
}
private void addGreenMarker(Date newDate, LatLng latLng) {
SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(dt.format(newDate));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(markerOptions);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Here is my Logcat Stack trace
Process: com.softtech.aqeel.childsequrity, PID: 3739
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
at com.softtech.aqeel.childsequrity.MapsActivity.getAllLocations(MapsActivity.java:247)
at com.softtech.aqeel.childsequrity.MapsActivity.access$000(MapsActivity.java:39)
at com.softtech.aqeel.childsequrity.MapsActivity$3.onDataChange(MapsActivity.java:228)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##16.0.4:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
i am trying to trace real time location of an android device for my project but at this point its giving me these exceptions. my app starts and when i open Maps Activity, map shows me for a little bit and then app automatically stops.
Use below code for creating object and casting.
LatLng latLng = new LatLng((double) singleLocation.get("latitude"), (double) singleLocation.get("longitude"));
use doubleValue() from Long
Change
LatLng latLng = new LatLng((Double) singleLocation.get("latitude"), (Double) singleLocation.get("longitude"));
to
LatLng latLng = new LatLng((Long) singleLocation.get("latitude").doubleValue(), (Long) singleLocation.get("longitude").doubleValue());
Get the latitude and longitude from singleLocation and convert it by this way and insert into the LatLng.
you must have to first convert Object value into String.
Like below
Map singleLocation = (Map) entry.getValue();
String latitude = String.valueOf(singleLocation.get("latitude"));
String longitude = String.valueOf(singleLocation.get("longitude"));
Double doublelat = Double.parseDouble(latitude);
Double doublelong = Double.parseDouble(longitude);
LatLng latlng = new LatLng(doublelat, doublelong);
You won't get any exception.

Take screenshot of the Displayed OpenStreetMap

I made an independent app to show the current user location using OpenStreetMaps. This is my Main Activity:
I used osmdroid 5.6.2
package com.example.re.osm;
public class MainActivity extends Activity {
private LocationManager locationManager;
private Location onlyOneLocation;
private final int REQUEST_FINE_LOCATION = 1234;
public GeoPoint startPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplicationContext();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
setContentView(R.layout.activity_main);
final MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
final IMapController mapController = map.getController();
mapController.setZoom(18);
CurrentLocation.requestSingleUpdate(this,
new CurrentLocation.LocationCallback() {
#Override public void onNewLocationAvailable(GPSCoordinates location) {
Log.d("Location", "my location is " + location.latitude + " : " + location.longitude);
startPoint = new GeoPoint(location.latitude, location.longitude);
// My Location Overlay
Marker marker=new Marker(map);
marker.setPosition(startPoint);
marker.setTitle("Your Location");
marker.showInfoWindow();
map.getOverlays().add(marker);
map.invalidate();
//This geopoint is currently static and shows a single location everytime the app is executed
mapController.setCenter(startPoint);
}
});
}
}
I need to take the screenshot of the map and display it. Any idea of how should I do it?
Thanks

showing google maps on android wear devices

I have developed an app to show ATM machines in your area. It works on my android phone but when I try to launch it on my android wearable watch it crashes. With the error "Binary XML File line #2 Error inflating class fragment" Any help is much appreciated.
Here is my xml code
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
and my activity:
public class MainActivity extends Activity {
private final String TAG = getClass().getSimpleName();
private GoogleMap mMap;
private String[] places;
private LocationManager locationManager;
private Location loc;
SharedPreferences sp;
static String distance;
public static final String PREF = "MyPrefs";
public static final String DISTANCE = "distance";
#Override
public void onResume() {
super.onResume();
sp = this.getSharedPreferences(PREF, Context.MODE_PRIVATE);
distance = sp.getString(DISTANCE, "1000");
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
currentLocation();
places=new String[1];
places[0]="ATM";
mMap.setMyLocationEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>> {
private ProgressDialog dialog;
private Context context;
private String places;
private double longitude;
private double latitude;
public GetPlaces(Context context, String places) {
this.context = context;
this.places = places;
}
#Override
protected void onPostExecute(ArrayList<Place> result) {
super.onPostExecute(result);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
if (dialog.isShowing()) {
dialog.dismiss();
}
for (int i = 0; i < result.size(); i++) {
mMap.addMarker(new MarkerOptions()
.title(result.get(i).getName())
.position(
new LatLng(result.get(i).getLatitude(), result
.get(i).getLongitude()))
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin))
.snippet(result.get(i).getVicinity()));
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)) // Sets the center of the map to
// Mountain View
.zoom(14) // Sets the zoom
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
protected ArrayList<Place> doInBackground(Void... arg0) {
PlacesService service = new PlacesService(
"xxxxxxxxxxxxx");
ArrayList<Place> findPlaces = service.findPlaces(loc.getLatitude(),
loc.getLongitude(), places, distance);
for (int i = 0; i < findPlaces.size(); i++) {
Place placeDetail = findPlaces.get(i);
Log.e(TAG, "places : " + placeDetail.getName());
}
return findPlaces;
}
}
private void currentLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager
.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
locationManager.requestLocationUpdates(provider, 0, 0, listener);
} else {
loc = location;
new GetPlaces(MainActivity.this, places[0].toLowerCase().replace(
"-", "_")).execute();
Log.e(TAG, "location : " + location);
}
}
private LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "location update : " + location);
loc = location;
locationManager.removeUpdates(listener);
}
};
}
Unfortunately, MapFragment and GoogleMap (along with the entirely of the Google Maps Android API) is currently not supported on Android Wear devices.

find out current position in OSMdroid

I want to find map of my current position and update it when i move via showing a icon in OSMdroid.I find no problem when give specific location latitude and longitude and drawing icon but there are two errors when i give current location latitude and longitude.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
setContentView(R.layout.main);
mMapView = (MapView) this.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mapController = this.mMapView.getController();
mapController.setZoom(15);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = mLocMgr.getBestProvider(criteria, true);
Location location = mLocMgr.getLastKnownLocation(provider);
GeoPoint mypoint = new GeoPoint(location.getLatitude(), location.getLongitude()); // centre map here
GeoPoint mypointicon = new GeoPoint(location.getLatitude()+1000, location.getLongitude()+1000); // icon goes here
mapController.setCenter(mypoint);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100,
this);
ArrayList<OverlayItem> items=new ArrayList<OverlayItem>();
items.add(new OverlayItem("Here", "Sample Description", mypointicon));
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
Toast.makeText(
MapOverLayGiveActivity.this,
"Item '" + item.mTitle, Toast.LENGTH_LONG).show();
return true; // We 'handled' this event.
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
Toast.makeText(
MapOverLayGiveActivity.this,
"Item '" + item.mTitle ,Toast.LENGTH_LONG).show();
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.mMyLocationOverlay);
mMapView.invalidate();
}
Error:
java.lang.NullPointerException
java.lang.RunTimeException
What's wrong in my code and how can i do that? thanks...
To follow location changes, implement LocationListener as below:
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
currentLocation = new GeoPoint(location);
displayMyCurrentLocationOverlay();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Inside onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if( location != null ) {
currentLocation = new GeoPoint(location.getLatitude(), location.getLongitude());
}
}
and displayMyCurrentLocationOverlay method:
private void displayMyCurrentLocationOverlay() {
if( currentLocation != null) {
if( currentLocationOverlay == null ) {
currentLocationOverlay = new ArrayItemizedOverlay(myLocationMarker);
myCurrentLocationOverlayItem = new OverlayItem(currentLocation, "My Location", "My Location!");
currentLocationOverlay.addItem(myCurrentLocationOverlayItem);
mapView.getOverlays().add(currentLocationOverlay);
} else {
myCurrentLocationOverlayItem.setPoint(currentLocation);
currentLocationOverlay.requestRedraw();
}
mapView.getController().setCenter(currentLocation);
}
}
You use this.myLocationOverlay - and because of that the osmDroid draw the current location - but for update the location you must use a location listener. Also, you must remove previous overlay from the map using mapView.getOverlays.clear() function
Well, let's say that you don't have acces to internet or GPS. In my opinion is safe to have a default point on the map.
In this code I check for a valid location. If is null, then I use DEFAULT values.
In my application I have no problems. I also draw a navigation path on the map, even if my location is changed.
{
Location location = null;
for (String provider : locationManager.getProviders(true))
{
location = locationManager.getLastKnownLocation(provider);
if (location != null)
{
//location.setLatitude(MAP_DEFAULT_LATITUDE);
//location.setLongitude(MAP_DEFAULT_LONGITUDE);
locationManager.requestLocationUpdates(provider, 0, 0, mUpdateHandler);
break;
}
}
//add car position
if (location == null)
{
location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(MAP_DEFAULT_LATITUDE);
location.setLongitude(MAP_DEFAULT_LONGITUDE);
updateCarPosition(new GeoPoint(location));
}
}
if you test on Emulator then remember use DDMS to set your current lat & long. if you don't, the getLastKnownLocation will return null

Categories

Resources