Unable To Call Task Within A Thread - android

I am trying to display multiple pin locations on the map i.e. my location and another location I get from the cloud server.
Based on the code below:
I keep getting a NullPointer Error message when I try to tokenize my string. This implies that my CloudTask activity is never fired.... I can't figure out why and the Eclipse Debugger won't step through the threads...any help is appreciated.
public class MapsActivity extends com.google.android.maps.MapActivity {
private static final String TAG = null;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
private MyLocationOverlay otherLocationOverlay;
private Handler handler;
private String message;
StringTokenizer tokens;
Integer p1 = null;
Integer p2;
GeoPoint point;
static Context mContext = null;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500,
0,(LocationListener) new GeoUpdateHandler());
//new Intent("android.intent.action.LOCATION_CHANGED");
//(LocationListener) new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
handler = new Handler();
// new AsyncTask<Void, Void, String>() {
myLocationOverlay.runOnFirstFix(new Runnable(){
public void run(){
MyRequestFactory requestFactory = Util.getRequestFactory(mContext,
MyRequestFactory.class);
final CloudTask1Request request = requestFactory.cloudTask1Request();
Log.i(TAG, "Sending request to server");
request.queryTasks().fire(new Receiver<List<TaskProxy>>() {
#Override
public void onSuccess(List<TaskProxy> taskList) {
//message = result;
message = "\n";
for (TaskProxy task : taskList) {
message += task.getId()+","+task.getNote()+",";
}
}
});
//return message;
//}
if(message.length() == 0){
Log.i("MESSAGE","Did not get any points from cloud");
}
tokens = new StringTokenizer(message,",");
tokens.nextToken();
p1 = Integer.parseInt(tokens.nextToken());
p2 = Integer.parseInt(tokens.nextToken());
point = new GeoPoint(p1,p2);
mapView.getController().animateTo(point);
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
//Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
if (itemizedoverlay.size() > 0) {
mapView.getOverlays().add(itemizedoverlay);
}
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}

put these inside onSuccess()
if(message.length() == 0){
Log.i("MESSAGE","Did not get any points from cloud");
}
tokens = new StringTokenizer(message,",");
tokens.nextToken();
p1 = Integer.parseInt(tokens.nextToken());
p2 = Integer.parseInt(tokens.nextToken());
point = new GeoPoint(p1,p2);
mapView.getController().animateTo(point);

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.

Android: Google Maps API v1 to v2

I've got android app (source) which is using google maps api v1. Unfortunately I can't use it because I can't generate maps key for v1 api. And because of that maps are not showing.
Is there an easy way for changing source code to be compatible with v2 google maps api? I've tried this tutorial: http://www.vogella.com/articles/AndroidGoogleMaps/article.html but without bigger success (I'm newbie in android development)
public class MapviewGeolocation extends MapActivity implements LocationListener {
private MapView mapView;
private MapController mc;
public static float currentLatitude = Resources.lat;
public static float currentLongitude = Resources.lon;
// private MyLocationOverlay myLocation;
private List<Event> items;
SharedPreferences sp;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// STRICTMODE
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
sp = this.getPreferences(Context.MODE_PRIVATE);
items = new ArrayList<Event>();
final Location myCurrentLocation = this.getLastBestLocation();
if (myCurrentLocation != null) {
if (Resources.isByGps) {
currentLatitude = (float) myCurrentLocation.getLatitude();
currentLongitude = (float) myCurrentLocation.getLongitude();
}
} else {
currentLatitude = Resources.lat;
currentLongitude = Resources.lon;
}
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mc.setZoom(13);
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
MyLocationOverlay mylocationOverlay = new MyLocationOverlay(this,
mapView);
mylocationOverlay.enableMyLocation();
mapView.getOverlays().add(mylocationOverlay);
InitMapTask init_map_task = new InitMapTask();
init_map_task.execute();
}
#Override
protected void onResume() {
super.onResume();
String adres = sp.getString("adres", "");
if (adres.length() < 1) {
Resources.isByGps = true;
} else {
Resources.isByGps = false;
}
if (!Resources.isByGps) {
currentLatitude = sp.getFloat("lat", Resources.lat);
currentLongitude = sp.getFloat("lon", Resources.lon);
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 200, this);
}
mapView.refreshDrawableState();
mapView.invalidate();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (Resources.isByGps) {
locationManager.removeUpdates(this);
}
}
private void addOverlays() {
items = Resources.events;
}
public Drawable getDrawable(int population) {
Drawable drawable = null;
if (population < 300)
drawable = this.getResources().getDrawable(R.drawable.pins_rose);
else if ((300 <= population) && (500 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_bleu);
else if ((500 <= population) && (800 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_vert);
else if ((800 <= population) && (1000 > population))
drawable = this.getResources().getDrawable(R.drawable.pins_jaune);
else
drawable = this.getResources().getDrawable(R.drawable.pins_blanc);
return drawable;
}
private void addOverlay(MapItemizedOverlay itemizedOverlay) {
Event ev = itemizedOverlay.getLocation();
GeoPoint location = new GeoPoint((int) (ev.getLat() * 1E6),
(int) (ev.getLon() * 1E6));
OverlayItem overlayitem = new OverlayItem(location, ev.getTitle(),
ev.getCity());
itemizedOverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onLocationChanged(Location location) {
if (Resources.isTesting) {
Toast.makeText(
getBaseContext(),
"Localization changed - current: Latitude = "
+ currentLatitude + " Longitude = "
+ currentLongitude, Toast.LENGTH_LONG).show();
}
// if (Resources.isByGps) {
if (location != null) {
currentLatitude = (float) location.getLatitude();
currentLongitude = (float) location.getLongitude();
GeoPoint geo = new GeoPoint((int) (currentLatitude * 1e6),
(int) (currentLongitude * 1e6));
mc.animateTo(geo);
}
// }
mapView.invalidate();
}
#Override
public void onProviderDisabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is off...", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
if (Resources.isTesting)
Toast.makeText(this, "GPS is on...", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (Resources.isTesting)
Toast.makeText(this, "GPS status changed...", Toast.LENGTH_LONG)
.show();
}
public class InitMapTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(MapviewGeolocation.this);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
addOverlays();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
for (int i = 0; i < items.size(); i++) {
int color = 0;
Drawable drawable = getDrawable(400);
MapItemizedOverlay itemizedOverlay = new MapItemizedOverlay(
drawable, mapView, MapviewGeolocation.this, color,
items.get(i), currentLatitude, currentLongitude);
addOverlay(itemizedOverlay);
}
mapView.invalidate();
progress.dismiss();
}
}
/**
* #return the last know best location
*/
private Location getLastBestLocation() {
LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location locationGPS = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
long GPSLocationTime = 0;
if (null != locationGPS) {
GPSLocationTime = locationGPS.getTime();
}
long NetLocationTime = 0;
if (null != locationNet) {
NetLocationTime = locationNet.getTime();
}
if (0 < GPSLocationTime - NetLocationTime) {
return locationGPS;
} else {
return locationNet;
}
}
// action for bottom menu
public void actionLista(View v) {
Intent i = new Intent(this, ListviewActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionMapa(View v) {
Intent i = new Intent(this, MapviewGeolocation.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
public void actionSettings(View v) {
Intent i = new Intent(this, Settings.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
}

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

getting location from service but myLocationOverlay doesn't work

I have a MapActivity that have to display my current position on the map using myLocationOverlay i get the location from a service.
Here is my Activity:
public class ShowMapActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlayUtility itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
private double latitude;
private double longitude;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_showmap);
Intent serviceIntent = new Intent(this, LocationService.class);
serviceIntent.setAction("startListening");
startService(new Intent(this, LocationService.class));
// check if the GPS is on
// isGPSEnable();
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_MAP);
registerReceiver(updateReceiver, filter);
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14);
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
}
#Override
protected boolean isRouteDisplayed() {
return true;
}
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private BroadcastReceiver updateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
longitude = intent.getDoubleExtra("long", 0);
latitude = intent.getDoubleExtra("lat", 0);
Log.e("LOCATION", "lat = " + latitude + " long = " + longitude);
}
};}
And here is my service :
public class LocationService extends Service implements LocationListener {
private final String UPDATE_MAP = "com.livetrekker.activities.UPDTAE_LOCATION";
private LocationManager locationManager;
private String provider;
private Location location;
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
Log.e("Service", "start location");
// if (intent.getAction().equals("startListening")) {
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
Log.e("LOCATION", "Provider " + provider + " has been selected");
onLocationChanged(location);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
// }
/*
* else { if (intent.getAction().equals("stopListening")) {
* locationManager.removeUpdates(this); locationManager = null; } }
*/
return START_STICKY;
}
#Override
public IBinder onBind(final Intent intent) {
return null;
}
#Override
public void onLocationChanged(final Location location) {
this.location = location;
double lng = location.getLongitude();
double lat = location.getLatitude();
Log.e("SERVICELOCATION", "lat : " + lat + " lng : " + lng);
Intent updateIntent = new Intent();
updateIntent.putExtra("long", lng);
updateIntent.putExtra("lat", lat);
updateIntent.setAction(UPDATE_MAP);
getApplicationContext().sendBroadcast(updateIntent);
}
public void onProviderDisabled(final String provider) {
}
public void onProviderEnabled(final String provider) {
}
public void onStatusChanged(final String arg0, final int arg1,
final Bundle arg2) {
}}
So the Location manager works fine i am able to get my latitude and longitude in my activity but the myLocationOverlay doesn't show up.
So is it possible to use that way to display my current position on the map ?
Thanks
EDIT:
I fixe my problem replacing
myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
by :
List overlays = mapView.getOverlays();
MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
myLocationOverlay.enableMyLocation();
overlays.add(myLocationOverlay);
Follow this code:
public class GoogleMapsActivity extends MapActivity {
public static final String TAG = "GoogleMapsActivity";
private MapView mapView;
private LocationManager locationManager;
Geocoder geocoder;
Location location;
LocationListener locationListener;
CountDownTimer locationtimer;
MapController mapController;
MapOverlay mapOverlay = new MapOverlay();
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.googlemap);
initComponents();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(16);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null) {
Toast.makeText(GoogleMapsActivity.this,
"Location Manager Not Available", Toast.LENGTH_SHORT)
.show();
return;
}
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onLocationChanged(Location l) {
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0) {
} else {
double lat = l.getLatitude();
double lng = l.getLongitude();
Toast.makeText(GoogleMapsActivity.this,
"Location Are" + lat + ":" + lng,
Toast.LENGTH_SHORT).show();
}
}
};
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 10f, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000) {
#Override
public void onTick(long millisUntilFinished) {
if (location != null)
locationtimer.cancel();
}
#Override
public void onFinish() {
if (location == null) {
}
}
};
locationtimer.start();
}
public MapView getMapView() {
return this.mapView;
}
private void initComponents() {
mapView = (MapView) findViewById(R.id.googleMapview);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends Overlay {
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pingreen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);
return true;
}
}
}
(Or) Follow this link: http://www.javacodegeeks.com/2011/02/android-google-maps-tutorial.html

I want to open my current location in google map

i want to open or focus to my current location in google map in android. I want my app to get coordinates and then give the name of my location from these coordinates and also in the end focus the current location map...
Kindly someone suggest me what and how to do and if possible give me some code sample. i m new to android :)
Thanks in advance! :)
here is the example of simple map display with current location
MyMap.java for display map
class MyMap extends MapActivity{
/** Called when the activity is first created. */
GeoPoint defaultPoint;
static GeoPoint point;
static MapController mc;
static MapView mapView;
static double curLat =0;
static double curLng =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
String coordinates[] = {"22.286595", "70.795685"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
mc = mapView.getController();
defaultPoint = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(defaultPoint);
mc.setZoom(13);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
Intent startService = new Intent(getApplicationContext(),ServiceLocation.class);
startService(startService);
}
public static void updateMap() {
if(ServiceLocation.curLocation!=null){
curLat = ServiceLocation.curLocation.getLatitude();
curLng = ServiceLocation.curLocation.getLongitude();
if(mapView!=null){
point = new GeoPoint((int)(curLat*1e6),(int)(curLng*1e6));
mc.animateTo(point);
mapView.invalidate();
}
}
}
#Override
protected boolean isRouteDisplayed(){
return false;
}
class MapOverlay extends com.google.android.maps.Overlay{
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
if(!shadow){
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
if(curLat==0 && curLng==0)
mapView.getProjection().toPixels(defaultPoint, screenPts);
else{
mapView.getProjection().toPixels(point, screenPts);
}
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.cur_loc);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
}
return true;
}
}
}
here is my background service code for fetching lat/lng using gps
class ServiceLocation extends Service{
private LocationManager locMan;
private Boolean locationChanged;
private Handler handler = new Handler();
public static Location centerLoc;
public static Location curLocation;
public static boolean isService = true;
LocationListener gpsListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (curLocation == null) {
curLocation = location;
locationChanged = true;
}else if (curLocation.getLatitude() == location.getLatitude() && curLocation.getLongitude() == location.getLongitude()){
locationChanged = false;
return;
}else
locationChanged = true;
curLocation = location;
if (locationChanged)
locMan.removeUpdates(gpsListener);
MyMap.updateMap();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// Log.w("GPS", "Location changed", null);
}
public void onStatusChanged(String provider, int status,Bundle extras) {
if (status == 0)// UnAvailable
{
} else if (status == 1)// Trying to Connect
{
} else if (status == 2) {// Available
}
}
};
#Override
public void onCreate() {
super.onCreate();
if (locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,100, 1, gpsListener);
} else {
this.startActivity(new Intent("android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS"));
}
centerLoc = new Location("");
curLocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);;*/
centerLoc = new Location("");
curLocation = getBestLocation();
if (curLocation == null)
Toast.makeText(getBaseContext(),"Unable to get your location", Toast.LENGTH_SHORT).show();
isService = true;
}
final String TAG="LocationService";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent i, int startId){
handler.postDelayed(GpsFinder,5000);// will start after 5 seconds
}
#Override
public void onDestroy() {
handler.removeCallbacks(GpsFinder);
handler = null;
Toast.makeText(this, "Stop services", Toast.LENGTH_SHORT).show();
isService = false;
}
public IBinder onBind(Intent arg0) {
return null;
}
public Runnable GpsFinder = new Runnable(){
public void run(){
Location tempLoc = getBestLocation();
if(tempLoc!=null)
curLocation = tempLoc;
handler.postDelayed(GpsFinder,5000);// register again to start after 5 seconds...
}
};
private Location getBestLocation() {
Location gpslocation = null;
Location networkLocation = null;
if(locMan==null)
locMan = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE);
try {
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,100, 1, gpsListener);
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(locMan.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,100, 1, gpsListener);
networkLocation = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} catch (IllegalArgumentException e) {
//Log.e(ErrorCode.ILLEGALARGUMENTERROR, e.toString());
Log.e("error", e.toString());
}
if(gpslocation==null && networkLocation==null)
return null;
if(gpslocation!=null && networkLocation!=null){
if(gpslocation.getTime() < networkLocation.getTime())
return networkLocation;
else
return gpslocation;
}
if (gpslocation == null) {
return networkLocation;
}
if (networkLocation == null) {
return gpslocation;
}
return null;
}
}

Categories

Resources