Animate to User Location (Android) - android

I am working on a project that has one feature to display (animate to) current user location and one hard coded location(given latitude and longitude). So far I have the hardcoded location working but I can't figure out how to get the user location. I've tried the location listener but my application keeps crashing after I run it. Does anybody have any advice on it? Much appreciated. Here's the code:
public class LocationsActivity extends MapActivity implements LocationListener {
MapView mapView;
MapController mc;
GeoPoint p;
LocationListener locListener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"52.67596","-8.64910"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint((int)(lat*1E6),(int)(lng*1E6));
OverlayItem overlayitem = new OverlayItem(p, "Limerick Institute of
Technology", "Moylish");
mc.animateTo(p);
mc.setZoom(17);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,
this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

if you are using MapActivity then you can use following code:
/**
* Set current location using MyLocationOverlay
*/
public void setCurrentLocation() {
myLocationOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
if (null != myLocationOverlay.getMyLocation()) {
/**
* Put extra sleep to avoid concurrentModicationException
*/
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
map.getController().animateTo(
myLocationOverlay.getMyLocation());
map.getOverlays().add(myLocationOverlay);
}
}
});
}
If you are using MapFragment then inside activity:
1. mapFragment.getMap().setMyLocationEnabled(true);
then call
private void moveMapToMyLocation() {
LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
Location loc = locMan.getLastKnownLocation(locMan.getBestProvider(crit,
false));
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude()))
.zoom(12.8f)
.build();
CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);
mapFragment.getMap().moveCamera(camUpdate);
}

I am building an app in ICS with a mapview within a Fragment.
After initializing the mapView in the activity class I pass it to the mapFragment which is the fragment that is used to display the map.
This is some of the code in my activity class :
mapView = new MapView(this, getString(R.string.mapsAPI));
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(this.myLocationOverlay);
mapView.postInvalidate();
public void calculateLocation() {
setLocationManager();
setLocation();
setGeoPoint(location);
}
public void setGeoPoint(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
geoPoint = new GeoPoint((int)( latitude * 1E6), (int)( longitude * 1E6 ));
}
public void setLocation() {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
public void setLocationManager() {
locationManager = ((LocationManager)getSystemService(Context.LOCATION_SERVICE));
}
and this is the code in my mapFragment class :
public class MapFragment extends Fragment
{
MapView gMap = null;
GeoPoint gPoint = null;
Location location = null;
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
gMap = ((NFCDemoActivity)getActivity()).getMapView();
return this.gMap;
}
public void onActivityCreated(Bundle paramBundle) {
super.onActivityCreated(paramBundle);
((NFCDemoActivity)getActivity()).calculateLocation();
gPoint = ((NFCDemoActivity)getActivity()).getGeoPoint();
gMap.setClickable(true);
gMap.setBuiltInZoomControls(true);
gMap.getController().setZoom(18);
gMap.getController().setCenter(gPoint);
}
public void onDestroy() {
super.onDestroy();
}
}
This will give you the user's current location.

Related

how to get address information when I click on a location icon

I have a set location code in my app. I want to get address information when I click on a location icon. How to use a click event
public class MyActivity extends MapActivity implements LocationListener
{
MapView mapView;
MapController mc;
private MyLocationOverlay myLocOverlay;
private String provider;
private LocationManager lm;
Drawable location = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
mapView = (MapView) findViewById(R.id.mview);
mc = mapView.getController();
mapView.setBuiltInZoomControls(true);
mc.setZoom(15);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(provider);
if(location != null){
onLocationChanged(location);
}
}
#Override
protected void onResume(){
super.onResume();
lm.requestLocationUpdates(provider, 400, 1, this);
myLocOverlay = new MyLocationOverlay(location.this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
myLocOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
mc.animateTo(myLocOverlay.getMyLocation());
}
});
mapView.postInvalidate();
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
myLocOverlay.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Android: my maps doesn't go to "my location"

i've created a map, but when on the phone, it doesn't move to my location (taken from gps). why?
Because i need to retrieve the user location, and in case i've found it, animate the map to that point and refresh it (to take the pin from the db). in negative case, i put the center to Milano.
public class Mappa extends MapActivity {
private MapView mapView;
double latitudine=0;
double longitudine=0;
int kilometri=20;
#Override
protected boolean isRouteDisplayed() {
return false;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mappa);
mapView = (MapView) findViewById(R.id.mapview);
MapController mapController = mapView.getController();
final MyLocationOverlay myLocationOverlay;
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pin_bioscalin);
MyOverlays itemizedoverlay = new MyOverlays(drawable, this);
// milano
latitudine = 45.464164;
longitudine = 9.190321;
GeoPoint mio_point = new GeoPoint((int)(latitudine*1E6), (int)(longitudine*1E6));
mapController.setCenter(mio_point);
mapController.animateTo(mio_point);
mapController.setZoom(11);
// GPS
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
// farmacie
Database_mio db=new Database_mio(this);
db.openDataBase();
Cursor data=db.elenco_negozi_mappa(latitudine,longitudine,kilometri);
data.moveToFirst();
do {
String id_farmacia = data.getString(data
.getColumnIndex("_id"));
String ragione_farmacia = data.getString(data
.getColumnIndex("ragione"));
String indirizzo_farmacia = data.getString(data
.getColumnIndex("ragione"));
int latitude_farmacia = (int) (data.getDouble(data
.getColumnIndex("lat")) * 1E6);
int longitude_farmacia = (int) (data.getDouble(data
.getColumnIndex("lng")) * 1E6);
GeoPoint point = new GeoPoint(latitude_farmacia,longitude_farmacia);
OverlayItem overlayitem = new OverlayItem(point,ragione_farmacia,indirizzo_farmacia);
itemizedoverlay.addOverlay(overlayitem);
} while (data.moveToNext());
mapOverlays.add(itemizedoverlay);
// disclamer
ImageView img = (ImageView) findViewById(R.id.image_mia_map);
img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent disclamer = new Intent(getParent(), Disclamer.class);
disclamer.putExtra("da_dove", "Mappa");
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("Disclamer", disclamer);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "La mia posizione: "+"Latitudine = "+loc.getLatitude()+"Longitudine = "+loc.getLongitude();
GeoPoint mio_point = new GeoPoint((int)(loc.getLatitude()*1E6), (int)(loc.getLongitude()*1E6));
mapView.getController().setCenter(mio_point);
mapView.getController().animateTo(mio_point);
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),"Gps disabilitato",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps abilitato",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
}
thanks to all.

Map View Marker in Current Location

I'm using this codes to view the current location of the user. But I also need to put a marker on it. I already saw a few tutorial regarding this but I still don't get it.
Here's my Activity
public class MapViewActivity extends MapActivity {
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.mapview);
//------------Start Displaying Map View--------------//
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint test= new GeoPoint(
lat,lng);
MapView mapview = (MapView) findViewById(R.id.mvmap);
MapController mapcontrol = mapview.getController();
mapcontrol.animateTo(test);
mapcontrol.setZoom(10);
mapview.setStreetView(true);
mapview.setSatellite(true);
mapview.setBuiltInZoomControls(true);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
use this class for ItemizedOverlay.
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
Log.e(" on tap item value ", "" + mapOverlays.get(index) + " Index "
+ index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
public void removeOverlay() {
mapOverlays.clear();
// this.populate();
}
}
In your MapViewActivity ,declare ,
CustomItemizedOverlay itemizedOverlay;
List<Overlay> mapOverlays;
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(test," "," ");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);

Android Radius circle around Geopoint

This is the code i written to get the gps coordinates of the mobile and point the place where you are. But in improvement I need to get 1km radius circle. How can i get it?
package m.a.p;
public class MappingActivity extends MapActivity {
MapController mControl;
GeoPoint GeoP;
MapView mapV;
Drawable d;
List<Overlay> overlaylist;
public double lat;
public double lng;
Button checkin, addplace;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in
// Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in
// Milliseconds
protected LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapV = (MapView) findViewById(R.id.mapview);
checkin = (Button) findViewById(R.id.check);
addplace = (Button) findViewById(R.id.addp);
overlaylist = mapV.getOverlays();
d = getResources().getDrawable(R.drawable.point);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
Button check = (Button) findViewById(R.id.check);
Button addplace = (Button) findViewById(R.id.addp);
Button nearby = (Button) findViewById(R.id.point);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView result = (TextView) findViewById(R.id.result);
result.setText("Checked the Plce");
}
});
addplace.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView result = (TextView) findViewById(R.id.result);
result.setText("Added the Plce");
}
});
nearby.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.result);
result.setText("Nearby the Plce");
}
});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format("You are Here");
Toast.makeText(MappingActivity.this, message, Toast.LENGTH_LONG)
.show();
GeoP = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mControl = mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(19);
OverlayItem overlayItem = new OverlayItem(GeoP, "You are Here",
"Point");
CustomPinpoint custom = new CustomPinpoint(d, MappingActivity.this);
custom.insertPinpoint(overlayItem);
overlaylist.add(custom);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
custompinpoint
public class CustomPinpoint extends ItemizedOverlay{
private ArrayList<OverlayItem> pinpoints = new ArrayList <OverlayItem>();
private Context c;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
}
public CustomPinpoint(Drawable m, Context context){
this(m);
c = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
return pinpoints.size();
}
public void insertPinpoint(OverlayItem item){
pinpoints.add(item);
this.populate();
}
}
Try to use a custom MapOverlay to draw your location and a circle around it whit overriding onDraw() method:
public class MyOwnLocationOverlay extends MyLocationOverlay{
private MapView mapView;
private Paint circlePainter;
private Point screenCurrentPoint;
private GeoPoint geoCurrentPoint;
private int meters;
public MyOwnLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
this.mapView = mapView;
}
// This method is used to get user submitted radius from our application
public void setMeters(int meters) {
this.meters = meters;
}
#Override
public synchronized boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when) {
// Set the painter to paint our circle. setColor = blue, setAlpha = 70 so the background
// can still be seen. Feel free to change these settings
circlePainter = new Paint();
circlePainter.setAntiAlias(true);
circlePainter.setStrokeWidth(2.0f);
circlePainter.setColor(0xff6666ff);
circlePainter.setStyle(Style.FILL_AND_STROKE);
circlePainter.setAlpha(70);
// Get projection from the mapView.
Projection projection = mapView.getProjection();
// Get current location
geoCurrentPoint = getMyLocation();
screenCurrentPoint = new Point();
// Project the gps coordinate to screen coordinate
projection.toPixels(geoCurrentPoint, screenCurrentPoint);
int radius = metersToRadius(geoCurrentPoint.getLatitudeE6() /1000000);
// draw the blue circle
canvas.drawCircle(screenCurrentPoint.x, screenCurrentPoint.y, radius, circlePainter);
return super.draw(canvas, mapView, shadow, when);
}
// hack to get more accurate radius, because the accuracy is changing as the location
// getting further away from the equator
public int metersToRadius(double latitude) {
return (int) (mapView.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));
}
}
see this link for more details

Android: using LocationManager and provider

I am new to android and was trying out stuff on my android emulator. While playing with the location manager and location listener, I could test the code of changing location using the emulator. The locationlistener catches the location change and moves to the specific location.
I now want to replicate the same test using my program, i.e. pass new coordinates every x seconds (may be through a thread ?) to the locationlistener, but through my program and not the emulator.
Can someone please suggest a way to go about implementing this functionality ?
The code for location listener that I found somewhere on the net and was trying:
private LocationListener locationListener;
private MapView mapView;
private MapController mc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,0,0,locationListener);
mapView = (MapView) findViewById(R.id.mpview);
mc = mapView.getController();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location locn) {
if (locn != null) {
GeoPoint point = new GeoPoint(
(int) (locn.getLatitude() * 1E6),
(int) (locn.getLongitude() * 1E6));
mc.animateTo(point);
mapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
Thanks!

Categories

Resources