Take screenshot of the Displayed OpenStreetMap - android

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

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.

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

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.

get the latitude and longitude of a clicked location on the map in osmdroid

I've managed to write an android app using it to trace user location and show it on the map using a marker. Here is the relevant code:
public class MainActivity extends Activity implements LocationListener {
public MapView mapView;
private LocationManager locationManager;
MyItemizedOverlay myItemizedOverlay = null;
Drawable marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setUseDataConnection(false);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(false);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.getController().setZoom(16); // set initial zoom-level, depends
// on your need
marker = getResources().getDrawable(android.R.drawable.star_on);
int markerWidth = 1;
int markerHeight = 1;
marker.setBounds(0, markerHeight, markerWidth, 0);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this); // You can also use LocationManager.GPS_PROVIDER and
// LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapView.getController().setCenter(point);
mapView.getController().animateTo(point);
mapView.invalidate();
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().clear();
mapView.getOverlays().add(myItemizedOverlay);
myItemizedOverlay.addItem(point, "myPoint1", "myPoint1");
TextView tv1 = (TextView) findViewById(R.id.myLat);
tv1.setText("Lat is " + lat);
TextView tv2 = (TextView) findViewById(R.id.myLong);
tv2.setText("Long is " + lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Now I need a way of getting latitude and longitude properties of a clicked location on the map.
I mean I need something similar to the following code(which exists for google map api) in osmdroid.
google.maps.event.addListener(map, 'click', function(event) {
YourHandler(event.latLng);});
You have to create an Overlay and override the onSingleTapConfirmed.
Try this:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
final Drawable marker = getApplicationContext().getResources().getDrawable(R.drawable.markericon);
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
System.out.println("- Latitude = " + latitude + ", Longitude = " + longitude );
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
}else{
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
// dlgThread();
return true;
}
};
mapView.getOverlays().add(touchOverlay);
If you implement MapEventsReceiver you can use the singleTapConfirmedHelper() function which directly gives you a GeoPoint object of the clicked location. Here is an example:
public class MapActivity extends AppCompatActivity implements MapEventsReceiver {
...
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
mapController.animateTo(p);
return true;
}
}

Android: How do I display users current location in my app, using google maps?

How do I display users current location in my app, using google maps? I would like to show users current location using mobile network or, if available, GPS. I didn't find any tutorials that could help me or they were too hard to understand.
Here's the code of my Map.java activity, could you just give me the code I need? Thanks!
import java.util.List;
public class Map extends MapActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
MapController mc = mapView.getController();
String coordinates[] = {"54.6738310", "025.2740480"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
GeoPoint p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(13);
mapView.invalidate();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,this);
GeoPoint point = new GeoPoint(30443769,-91158458);
OverlayItem overlayitem = new OverlayItem(point, "Laissez les bon temps rouler!", "I'm in Louisiana!");
GeoPoint point2 = new GeoPoint(17385812,78480667);
OverlayItem overlayitem2 = new OverlayItem(point2, "Namashkaar!", "I'm in Hyderabad, India!");
itemizedoverlay.addOverlay(overlayitem);
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
}
you need to combine your mapview with a location manager. Thanks to that, you can get the user position and paint it in the map (as another overlay). Take a look into this link which is a tutorial for getting the position.
public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener, LocationListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Marker mCurrLocationMarker;
private LocationRequest mLocationRequest;
private ArrayList<LatLng> routePoints;
private Polyline line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
routePoints = new ArrayList<LatLng>();
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setSmallestDisplacement(0.1F); //added
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //changed
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
// Add a marker in Sydney and move the camera
LatLng india = new LatLng(20.5937, 78.9629);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
PolylineOptions pOptions = new PolylineOptions()
.width(5)
.color(Color.GREEN)
.geodesic(true);
for (int z = 0; z < routePoints.size(); z++) {
LatLng point = routePoints.get(z);
pOptions.add(point);
}
line = mMap.addPolyline(pOptions);
routePoints.add(latLng);
}
}

Categories

Resources