Cannot Determine Location In Android - android

I am trying to create Android where showing the user's location in Map-view.But when run this app it says "Can't Determinate Location" .I am in stuck .Can you help me with my code or a link to a guide on how to implement this correctly?
Here is my code:
public class MyMapLocationActivity extends MapActivity {
private MapView mapView;
private MyLocationOverlay myLocationOverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// main.xml contains a MapView
setContentView(R.layout.main);
// extract MapView from layout
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// create an overlay that shows our current location
myLocationOverlay = new FixedMyLocationOverlay(this, mapView);
// add this overlay to the MapView and refresh it
mapView.getOverlays().add(myLocationOverlay);
mapView.postInvalidate();
// call convenience method that zooms map on our location
zoomToMyLocation();
}
#Override
protected void onResume() {
super.onResume();
// when our activity resumes, we want to register for location updates
myLocationOverlay.enableMyLocation();
}
#Override
protected void onPause() {
super.onPause();
// when our activity pauses, we want to remove listening for location updates
myLocationOverlay.disableMyLocation();
}
/**
* This method zooms to the user's location with a zoom level of 10.
*/
private void zoomToMyLocation() {
GeoPoint myLocationGeoPoint = myLocationOverlay.getMyLocation();
if(myLocationGeoPoint != null) {
mapView.getController().animateTo(myLocationGeoPoint);
mapView.getController().setZoom(10);
}
else {
Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}}
FixedMyLocationOverlay.java
public class FixedMyLocationOverlay extends MyLocationOverlay {
private boolean bugged = false;
private Drawable drawable;
private Paint accuracyPaint;
private Point center;
private Point left;
private int width;
private int height;
public FixedMyLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
}
#Override
protected void drawMyLocation(Canvas canvas, MapView mapView,
Location lastFix, GeoPoint myLocation, long when) {
if(!bugged) {
try {
super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
} catch (Exception e) {
// we found a buggy phone, draw the location icons ourselves
bugged = true;
}
}
if(bugged) {
if(drawable == null) {
accuracyPaint = new Paint();
accuracyPaint.setAntiAlias(true);
accuracyPaint.setStrokeWidth(2.0f);
drawable = mapView.getContext().getResources().getDrawable(R.drawable.ic_maps_indicator_current_position);
width = drawable.getIntrinsicWidth();
height = drawable.getIntrinsicHeight();
center = new Point();
left = new Point();
}
Projection projection = mapView.getProjection();
double latitude = lastFix.getLatitude();
double longitude = lastFix.getLongitude();
float accuracy = lastFix.getAccuracy();
float[] result = new float[1];
Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
float longitudeLineDistance = result[0];
GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6));
projection.toPixels(leftGeo, left);
projection.toPixels(myLocation, center);
int radius = center.x - left.x;
accuracyPaint.setColor(0xff6666ff);
accuracyPaint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
accuracyPaint.setColor(0x186666ff);
accuracyPaint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
drawable.setBounds(center.x - width/2, center.y - height/2, center.x + width/2, center.y + height/2);
drawable.draw(canvas);
}
}}
In manifest file i add below this:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Below link could be useful, it worked for me:
http://ramsandroid4all.blogspot.in/2013/06/google-maps-android-api-v2-showing.html
The above link explains 2 things,
How to implement Google map version 2 in Android.
How to implement location listener to determine user location.
The overall code shows how to get your current location using NETWORK_PROVIDER and display it by a marker on Google map. Your device need to have Google map installed and internet connection to run properly. The below code is the most important part to determine user location when he changes his position:
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}

Related

How to get Current location with Zoom Extent

I am getting current location in my application with using LocationListener.But problem is when i apply zoom to map,first time the zoom shows current location but after some time the zoom goes to sea.I am unable to find solution for this from last 3 day,please tell me any one
My Activity
loc = mMapView.getLocationDisplayManager();
loc.setAutoPanMode(AutoPanMode.LOCATION);
loc.setLocationListener(new MyLocationListener(LaunchingMapActivity.this,mMapView));
loc.start();
mLocation = loc.getPoint();
Log.e("mLocation", ""+mLocation);
mapLocatiomFromLoc = loc.getLocation();
double longitude=mapLocatiomFromLoc.getLongitude();
double latitude=mapLocatiomFromLoc.getLatitude();
p=new Point((float)longitude,(float)latitude);
MyLocationListener:
public class MyLocationListener implements LocationListener {
Geometry mLocation = null;
private MapView mMapView;
private Context mContext;
public MyLocationListener(Context context,MapView mapView) {
super();
this.mMapView=mapView;
}
/**
* If location changes, update our current location. If being found for
* the first time, zoom to our current position with a resolution of 20
*/
public void onLocationChanged(Location loc1) {
if (loc1 == null)
return;
boolean zoomToMe = (mLocation == null) ? true : false;
mLocation = new Point(loc1.getLongitude(), loc1.getLatitude());
Log.e("ONCHANGEmLocation", ""+mLocation);
if (zoomToMe) {
Point mPoint = (Point) GeometryEngine.project(mLocation, SpatialReference.create(20439)
,SpatialReference.create(20439));
Log.e("mPoint",""+ mPoint);
// graphic = new Graphic((Geometry) p, (Symbol) sms, hm);
// locationLayer.addGraphic(graphic);
// mMapView.zoomToResolution(mPoint, 20.0);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(mContext, "GPS Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(mContext, "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
you need to setCenter() with your current location
try the following code
MapController mc;
public void onLocationChanged(Location location) {
List<Overlay> overlays = mapView.getOverlays();
myLocOverlay = new MyLocationOverlay(this, mapView);
overlays.add(myLocOverlay);
myLocOverlay.enableMyLocation();*
// definitely need what's below
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mc.setCenter(point);
mapView.invalidate();
}
In ArcGIS you can show current user location like this:
LocationDisplayManager mLDM = mMapView.getLocationDisplayManager();
mLDM.setShowLocation(true);

Map overlay not updating

i am trying to draw the path as the farmer moves around his farm the below are my classes ,my problem is when i start tracing the line moves even when the user is not moving and path is not updating as he moves
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
mainactivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
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;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}
Can you confirm that you're always using the GPS to trace the route? Otherwise you might get incorrect results and your patch might get drawn like on Apple maps. For those cases always try using the GPS, I'm sure you don't want incorrect path to be drawn on the map. The network provider can triangulate a relative point on the map, but it will be incorrect 99% of the time in this case, because the position is relative.
Cheers

Overlay not drawing on the right spot

I have an extremely weird issue.
First of all, when I zoom in and out of a MapView, the marker (overlay) moves to incorrect places (doesn't work well with scaling).
Secondly, the market is being drawn at the wrong position!
I'll post code below but first listen to this:
I'm in Islamabad. The GeoCoder also tells me I'm in Islamabad. But when I draw a circle around my location using overlays, it draws it in a city that's 100s of kilometers away.
Kindly help me with both the problems.
Here's the activity:
public class LocatePickup extends MapActivity implements LocationListener {
Geocoder gc;
MapView mapView;
MapController mc;
GeoPoint p;
double lat = 0;
double lng = 0;
LocationManager lm;
WebMethods wm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate_pickup);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);
Location l = new Location(LocationManager.NETWORK_PROVIDER);
l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mc = mapView.getController();
p = new GeoPoint((int) (l.getLatitude()), (int) (l.getLongitude()));
mc.setCenter(p);
mc.setZoom(14);
MapOverlay myLocationOverlay = new MapOverlay();
List<Overlay> list = mapView.getOverlays();
list.add(myLocationOverlay);
gc = new Geocoder(this);
try {
List<Address> address = gc.getFromLocation(l.getLatitude(), l.getLongitude(), 1);
Toast.makeText(this, ""+address.get(0).getAddressLine(1), 1).show();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
Paint paint = new Paint();
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 218, 28, 28);
paint.setStyle(Paint.Style.STROKE);
//Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
canvas.drawCircle(myScreenCoords.x, myScreenCoords.y, 15, paint);
//(bmp, myScreenCoords.x, myScreenCoords.y - 256, paint);
canvas.drawText("Hey!", myScreenCoords.x, myScreenCoords.y, paint);
return true;
}
}
#Override
public void onLocationChanged(Location arg0) {
if(arg0 != null) {
Log.d("New Location: ", arg0.getLatitude() + " - " + arg0.getLongitude());
lat = arg0.getLatitude();
lng = arg0.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}
}
#Override
public void onProviderDisabled(String provider) {
// empty
}
#Override
public void onProviderEnabled(String provider) {
// empty
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//empty
}
}
Once the code is complete, I'd like the user to be able to tap a spot on the map and get its address (the marker should move to that spot as well). But it should be accurate.
Since no one answered this question correctly..
For some reason, the normal Overlay class wasn't working for me the way it should have. I switched to ItemizedOverlay and now everything is perfect.
I'm no Android expert so I'd like someone with better experience to comment on this but, I feel that ItemizedOverlay is much better than the simple Overlay. With itemizedoverlay, zooming in and out of the mapview with an object drawn at a fixed point works the way it should, the pin (object) stays exactly where it should stay (that wasn't the case previously).
Here's some code for those who are looking for it. This is of course incomplete, and for a specific purpose, but you get the general idea.
`class CustomOverlay extends com.google.android.maps.ItemizedOverlay
{
private ArrayList mOverlays = new ArrayList();
Context mContext;
public CustomOverlay(Drawable defaultMarker)
{
super(defaultMarker);
}
public void addOverlay(OverlayItem overlay)
{
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i)
{
return mOverlays.get(i);
}
#Override
public int size()
{
return mOverlays.size();
}
public CustomOverlay(Drawable defaultMarker, Context context)
{
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1)
{
p = mapView.getProjection().fromPixels((int) event.getX(),
(int) event.getY());
gc = new Geocoder(getBaseContext(), Locale.getDefault());
try
{
address = gc.getFromLocation(
(double) p.getLatitudeE6() / 1E6,
(double) p.getLongitudeE6() / 1E6, 1);
addressfound = true;
}
catch (IOException e)
{
addressfound = false;
e.printStackTrace();
}
if (address.size() != 0)
{
l1 = address.get(0).getAddressLine(0);
l2 = address.get(0).getAddressLine(1);
l3 = address.get(0).getAddressLine(2);
}
OverlayItem point = new OverlayItem(p, "Location", l1 + ", "
+ l2 + ", " + l3);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = getBaseContext().getResources()
.getDrawable(R.drawable.androidmarker);
CustomOverlay itemizedoverlay = new CustomOverlay(drawable,
getBaseContext());
itemizedoverlay.addOverlay(point);
mapOverlays.clear();
mapOverlays.add(itemizedoverlay);
mapView.invalidate();
}`

Bubble pop up box

Google map, it allows us to pin-point any location we want. After pin-pointing, there will be this "Bubble" pop up box at the top of the push-pin. May i know how to do the pop up window box? Any codes to show? I am using alert dialog box now, but i want it to be "Bubble" pop up window instead.
List<Overlay> mapOverlays = mapView.getOverlays();
MapOverlay mapOverlay = new MapOverlay();
mapOverlays.add(mapOverlay);
// obtain gps location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
// LocationManager.GPS_PROVIDER,
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
k = new GeoPoint((int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(k);
mc.setZoom(18);
// Add a location marker
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listofOverlays = mapView.getOverlays();
listofOverlays.clear();
listofOverlays.add(mapOverlay);
// invalidate() method forces the MapView to be redrawn
mapView.invalidate();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean onTap(final GeoPoint p, MapView mapView) {
// TODO Auto-generated method stub
k = p;
mc = mapView.getController();
mc.animateTo(p);
mapView.invalidate();
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0)
.getMaxAddressLineIndex(); i++)
add += addresses.get(0).getAddressLine(i) + "\n";
txtAddress.setText("Address: " + add);
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
if (k != null) {
// ---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(k, screenPts);
// ---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.passenger);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
}
return true;
}
}
}
I'm currently working on a mapping application where I also needed to display 'Bubble' popups and the following blog posts helped me quite a bit.
This first post shows how to use a 9-patch image embedded in a view to produce a popup. The code is ok but does leave a number of questions unanswered, some commenters have requested some additional source code for clarification.
This post from the Android Developers blog explains what a 9 patch image is an how to create one.
Using these two posts I was able to pull some code together which works well so hopefully you will be able to manipulate it to fit your needs too.
Sounds like you are looking for the InfoWindow. By the way, in newer versions of the API, they do not have rounded corners (they look more like boxes and less like bubbles). You can restore the old ones by requesting a previous version of the API in the javascript URL that loads the maps API.
Google doesn't provide an API to do this, take a look at this. Victor's answer gives a link to open source code which fits the bill.

mock location in android

I am using the following to mock my location in Android.
public class GPSwork extends Activity implements LocationListener{
LocationManager locationManager;
String mocLocationProvider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mocLocationProvider = LocationManager.GPS_PROVIDER;
setLocation(28.574853,78.063201);
}
public void setLocation(double latitude, double longitude) {
locationManager.addTestProvider(mocLocationProvider, false, true, false, false, false, false, false, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, this);
Location loc = new Location(mocLocationProvider);
loc.setTime(System.currentTimeMillis());
loc.setLatitude(latitude);
loc.setLongitude(longitude);
locationManager.setTestProviderLocation(mocLocationProvider, loc);
}
public void onLocationChanged(Location location) {
// 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
}
}
But it's not working. I want to see it in real device and the bubble blinking in that location, but I didnt get anything. Please correct my code, and help me out. I used the permissions.
I want build an application similatiom to location spoofer.Actually when we open google maps it will show our current location with blue blinking at our location..similarly if i changed the coordinates i.e, latitude and latitude it has to show that am at that location with blue blinking,
![alt text][1]
this is the screen short..
My XML fine is
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0Sy8vgJlQkFxcisUAkrxu3xN33dqFgBetCg4jxg"
/>
This is a basic pattern for an app that uses google maps:
public class MapsActivity extends MapActivity
{
MapView mapView;
MapController mc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mapView = (MapView)findViewById(R.id.mapView);
//zoom controlls
mc = mapView.getController();
mc.setZoom(12);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
In your AndroidManifest.xml file add:
<uses-library android:name="com.google.android.maps" />
and:
<uses-permission android:name="android.permission.INTERNET" />
To display your particular location add this to the onCreate method:
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(17);
mapView.invalidate();
Finally you need to set your marker using a map overlay. Add the following class to your MapsActivity class:
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);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.my_bubble);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
In this draw method you can to some marker animation if you want to. Now you have to add the overlay to your map:
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
This is a quick overview. You will need a google api key to work with google maps api. A detailed tutorial on google maps api can be found here, Using Google Maps in Android
Here is how to handle gps in android. It is a bad solution to make your main activity listen to location updates. Use and modify the following class:
public MyGPS implements LocationListener{
public LocationManager lm = null;
private MainActivity SystemService = null;
//lat, lng
private double mLongitude = 0;
private double mLatitude = 0;
public MyGPS(MainActivity sservice){
this.SystemService = sservice;
this.startLocationService();
}
public void startLocationService(){
this.lm = (LocationManager) this.SystemService.getSystemService(Context.LOCATION_SERVICE);
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
}
public void onLocationChanged(Location location) {
location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
this.mLongitude = location.getLongitude();
this.mLatitude = location.getLatitude();
} catch (NullPointerException e) {
Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null);
}
}
}
In your onCreate method make an instance of this class and the locationlistener will start to listen for gps updates. But you can not access lng and lat since you do not know from your activity wheather they are set or null. So you need a handler that sends a message to your main activity:
Modify in the following method:
public void onLocationChanged(Location location) {
location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
this.mLongitude = location.getLongitude();
this.mLatitude = location.getLatitude();
Message msg = Message.obtain();
msg.what = UPDATE_LOCATION;
this.SystemService.myViewUpdateHandler.sendMessage(msg);
} catch (NullPointerException e) {
Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null);
}
}
In your main activity add this:
Handler myViewUpdateHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_LOCATION:
//access lat and lng
}));
}
super.handleMessage(msg);
}
};
I think you have to extend the MyLocationOverlay class and Override the onDraw and change the location to your desired location and then call the superclass.onDraw method.

Categories

Resources