Send your current location from one activity to another - android

i would like to obtain my lĨocation in one activity, then send it to another (when i click button) and there show my location on maps.
Here's my code (the problem is,map doesn't animate to my current location, I believe first activity doesn't obtain current location and sends null to second activity):
public class ActivityMain extends MapActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private GeoPoint currentGeoPoint = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitymain);
try{
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new getLocation();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
catch (NullPointerException e){
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onButton1Click(View view) {
Intent intent = new Intent(ActivityMain.this, ActivityMap.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(currentGeoPoint != null){
intent.putExtra("lat", currentGeoPoint.getLatitudeE6());
intent.putExtra("long", currentGeoPoint.getLongitudeE6());
}
else{
try{
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new getLocation();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
catch (NullPointerException e){
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
Context c = getApplicationContext();
c.startActivity(intent);
//Intent intent = new Intent(ActivityMain.this, ActivityMap.class);
//this.startActivity(intent);
}
public void onButton2Clik (View view){
Intent intent = new Intent(ActivityMain.this, ActivityListCategories.class);
this.startActivity(intent);
}
class getLocation implements LocationListener {
public void onLocationChanged(Location location) {
if (location != null){
GeoPoint currentPoint = getCurrentPoint(location);
currentGeoPoint = currentPoint;
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), getProvider() + " enabled", Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), getProvider() + " disabled", Toast.LENGTH_SHORT).show();
}
}
public GeoPoint getLastKnownPoint (){
GeoPoint lastKnownPoint = null;
Location lastKnownLocation = locationManager.getLastKnownLocation(getProvider());
if(lastKnownLocation != null){
lastKnownPoint = getCurrentPoint(lastKnownLocation);
}
return lastKnownPoint;
}
public GeoPoint getCurrentPoint (Location location){
GeoPoint currentPoint = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
return currentPoint;
}
public String getProvider() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String Provider = locationManager.getBestProvider(criteria, true);
return Provider;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
protected void onResume(){
super.onResume();
LocationManager newLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager = newLocationManager;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
protected void onPause(){
super.onPause();
locationManager.removeUpdates(locationListener);
}
protected void onDestroy(){
super.onDestroy();
locationManager.removeUpdates(locationListener);
}
}
and here is code for second activity
public class ActivityMap extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private LocationListener locationListener;
private GeoPoint currentGeoPoint;
private Location currentLocation = null;
private ClassMapOverlay currPos;
private ClassCustomItemizedOverlay<ClassCustomOverlayItem> mallsOverlay;
private List<ClassMall> malls;
// TODO: AsyncTAsk
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitymap);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
currentGeoPoint = new GeoPoint((int)(bundle.getDouble("lat") / 1E6),(int)(bundle.getDouble("long")/1E6));
animateToCurrentPoint(currentGeoPoint);
}
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
public GeoPoint getLastKnownPoint (){
GeoPoint lastKnownPoint = null;
Location lastKnownLocation = locationManager.getLastKnownLocation(getProvider());
if(lastKnownLocation != null){
lastKnownPoint = getCurrentPoint(lastKnownLocation);
}
return lastKnownPoint;
}
public GeoPoint getCurrentPoint (Location location){
GeoPoint currentPoint = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
return currentPoint;
}
public void animateToCurrentPoint(GeoPoint currentPoint){
mapController.animateTo(currentPoint);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
}
public void drawCurrPositionOverlay(){
List<Overlay> overlays = mapView.getOverlays();
overlays.remove(currPos);
Drawable marker = getResources().getDrawable(R.drawable.me);
currPos = new ClassMapOverlay(marker,mapView);
GeoPoint drawMyPoint = null;
if(currentGeoPoint==null){
drawMyPoint = getLastKnownPoint();
}
else {
drawMyPoint = currentGeoPoint;
}
OverlayItem overlayitem = new OverlayItem(drawMyPoint, "Moja adresa:", getAddress(currentLocation));
currPos.addOverlay(overlayitem);
overlays.add(currPos);
currPos.setCurrentLocation(currentLocation);
}
public void drawMallsOverlay(List <ClassMall> malls){
List <Overlay> overlays = mapView.getOverlays();
overlays.remove(mallsOverlay);
Drawable marker = getResources().getDrawable(R.drawable.malls);
mallsOverlay = new ClassCustomItemizedOverlay<ClassCustomOverlayItem>(marker, mapView);
if(malls.size() > 0){
for(ClassMall temp: malls ){
GeoPoint mallPoint = getLatLon(temp.getAddress());
ClassCustomOverlayItem overlayItem = new ClassCustomOverlayItem(mallPoint,temp.getName(),temp.getAddress(), temp.getUrl());
mallsOverlay.addOverlay(overlayItem);
//Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
}
}
overlays.add(mallsOverlay);
}
public String getProvider() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String Provider = locationManager.getBestProvider(criteria, true);
return Provider;
}
public String getAddress (Location location){
Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String sAddress = "";
try{
List <Address> address = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(address.size() > 0){
for(int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++){
sAddress += address.get(0).getAddressLine(i) + "\n";
}
}
}
catch (IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return sAddress;
}
public GeoPoint getLatLon (String address){
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
GeoPoint point = null;
List <Address> addresses = null;
try {
addresses = geoCoder.getFromLocationName(address, 1);
if(addresses.size() > 0){
point = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude()*1E6));
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return point;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
And please can you tell me how can i asynchronously obtain my current location ?

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
intent = new Intent(LegalSeeFoods.this, MapDemoActivity.class);
intent.putExtra("lat", location .latitude);
intent.putExtra("long", location .longitude);
startActivity(intent);
IN MapDemoActivity.class
mapView.getController().setCenter(point); <--- TO animate to location

Related

Can't Get Location using LocationManager in Background Service

I have created an application that stores your location in database at periodic time in Background service but, it doesn't get location. my code is...
public class LocationService extends Service {
private Double myLat, myLong;
private Location location;
private LocationManager locManager;
private LocationListener locationListener;
private boolean NETWORK_ENABLED, GPS_ENABLED, PASSIVE_ENABLED;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myLat = 0.00;
myLong = 0.00;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LocationService.this.location = location;
LocationService.this.myLat = location.getLatitude();
LocationService.this.myLong = location.getLongitude();
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
insertToDatabase();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
getMyCurrentLocation();
}
private void getMyCurrentLocation() {
location = null;
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NETWORK_ENABLED = false; GPS_ENABLED = false; PASSIVE_ENABLED = false;
NETWORK_ENABLED = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (NETWORK_ENABLED) {
Toast.makeText(getApplicationContext(), "Network Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 45 * 1000l, 1f, locationListener);
}
if (location == null) {
//setGPSOn();
GPS_ENABLED = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GPS_ENABLED) {
Toast.makeText(getApplicationContext(), "GPS Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 1f, locationListener);
}
//setGPSOff();
}
if (location == null) {
PASSIVE_ENABLED = locManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(PASSIVE_ENABLED) {
Toast.makeText(getApplicationContext(), "Passive Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0l, 1f, locationListener);
}
}
try {
location = locManager.getLastKnownLocation(locManager.getBestProvider(new Criteria(), true));
} catch(NullPointerException e) {}
if (location != null) {
myLat = location.getLatitude();
myLong = location.getLongitude();
insertToDatabase();
} else {
Location loc = null;
try {
loc = getLastKnownLocation(this);
} catch(NullPointerException e) {}
if (loc != null) {
myLat = loc.getLatitude();
myLong = loc.getLongitude();
insertToDatabase();
}
}
locManager.removeUpdates(locationListener);
}
private Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List<?> list = locationmanager.getAllProviders();
boolean i = false;
Iterator<?> iterator = list.iterator();
do {
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
else {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
}
this doesn't give me any location.... and my app is also doesn't Crash or gives any Exception.
I have properly register all permissions in Manifest file...
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
I can't find what to do?
any help will be appreciated
thanks in advance for Help...
I think your problem is that you remove the listener right away:
locManager.removeUpdates(locationListener); // comment this one out
in getMyCurrentLocation();
You should try to remove your listener in some other places.

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

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

How to get longitude and latitude by GPS in Android?

I can get longitude and latitude by network provider, but unable to get it by GPS. How can I do that?
public void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocation != null) {
gp1 = getGeoByLocation(mLocation);
gp2 = gp1;
refreshMapView();
if( !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000,
10, mLocationListener);
}else{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
10, mLocationListener);
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
Get lat long using GPS in every 10 min.
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Categories

Resources