Android: Google Maps API v1 to v2 - android

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

Related

android- google map is not showing

I've a very strange problem with using google map in my application , I've build an application , it shows the map in my phone and it has not problem but it doesn't show in another phone , it has a white screen like this :
and then it shows this:
on the same phone, in another app it shows map with no problem .
could you help me ?
this is my code :
public class Maps extends AppCompatActivity {
FetchCordinates fetchCordinates;
Intent locatorService = null;
MapView mMapView;
private GoogleMap googleMap;
Double lat = 0.0, lon = 0.0;
Typeface typeface;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
typeface = Func.getTypeFace(this);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mapBuilder();
try {
Bundle bl = getIntent().getExtras();
if (bl != null) {
lat =(bl.getDouble("lat"));
lon = (bl.getDouble("lon"));
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
} catch (Exception e) {
}
}
private void mapBuilder() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Maps.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
doGPS();
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
e.printStackTrace();
}
Button mapbutton=(Button)findViewById(R.id.mapbutton);
mapbutton.setTypeface(typeface);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor pref= settings.edit();
pref.putString("lat", lat+"");
pref.putString("lon", lon+"");
pref.commit();
onBackPressed();
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapBuilder();
} else {
MyToast.makeText(Maps.this, "دسترسی به جی پی اس غیرفعال است");
}
return;
}
}
}
public boolean stopService() {
if (this.locatorService != null) {
this.locatorService = null;
}
return true;
}
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
return alert;
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
try {
if(dialog!=null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
lat = lati;
lon = longi;
MyToast.makeText(Maps.this, "موقعیت شما با موفقیت ثبت شد");
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
googleMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 22));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
private void doGPS() {
try {
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
} else {
android.support.v7.app.AlertDialog.Builder a = new android.support.v7.app.AlertDialog.Builder(Maps.this);
a.setMessage(("جی پی اس خاموش است. آیا میخواهید روشن کنید؟"));
a.setPositiveButton(("بله"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
});
a.setNegativeButton(("خیر"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
if (mMapView != null && mMapView.getVisibility() == View.VISIBLE)
mapBuilder();
}
could you help me ?

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

Send your current location from one activity to another

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

Unable To Call Task Within A Thread

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

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