How to get Current location with Zoom Extent - android

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

Related

showing the current location through gps in android

I'm developing an app which should show the current location of device in google maps on Android.The Problem is I'm not getting the exact or near location of the device.
I have class for :
public class GPSLocatorActivity extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
// mapView.setStreetView(true);
// enable to show Satellite view
mapView.setSatellite(true);
// enable to show Traffic on map
mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
// myLocationOverlay=new MyLocationOverlay(this,mapView);
mapController = mapView.getController();
mapController.setZoom(16);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
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);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
}
I added the permisiions in Mainfest file :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I have added permisions and use exact Google Api key for maps.
Did you try like this..
using this you can get the latitude and longitude for the current location.then pass the value to get the map.
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
example links;;
link1
link2
link3
link4

How to get current location on google mapview in android [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In this my code i did not understand where i did mistake in my code .I did not get current location on map view with pin point image. How to get the Latitude & Latitude and pass in Geo point. then pass the value OverlayItem ..
public class HelloGoogleMaps2 extends MapActivity implements LocationListener{
private LocationManager locationManager;
private String provider;
int lat;
int lng;
MyLocationOverlay myLocOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("provider ","Provider "+provider);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
Log.d("location","Location "+location);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
// longitudeField.setText("Location not available");
}
List<Overlay> mapOverlays = mapView.getOverlays();
myLocOverlay = new MyLocationOverlay(this, mapView);
mapOverlays.add(myLocOverlay);
myLocOverlay.enableMyLocation();
GeoPoint point = new GeoPoint(lat, lng);
// mc.setCenter(point);
// mapView.invalidate();
Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
GeoPoint point = new GeoPoint(lat,lng);
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
//
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
//
public void onLocationChanged(Location location) {
lat = (int) (location.getLatitude()* 1E6);
lng = (int) (location.getLongitude()* 1E6);
// latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
}
//
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
//
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
//
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
The right code is this ,but also add uses-permissio ,Internet,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION and WRITE_EXTERNAL_STORAGE .user-library .
public class GoogleMapActivity extends MapActivity implements LocationListener {
private final static String TAG = GoogleMapActivity.class.getSimpleName();
private MyItemizedOverlay itemizedOverlay;
double lat;
double lng;
private String provider;
private LocationManager locationManager;
private MapView mapview;
Drawable drawable;
boolean sat = true;
boolean dra = true;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// fetch the map view from the layout
mapview = (MapView) findViewById(R.id.mapview);
// make available zoom controls
mapview.setBuiltInZoomControls(false);
// Use the location manager through GPS
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
Log.i(TAG, "Lattitude:" + lat);
Log.i(TAG, "Longitude:" + lng);
Toast.makeText(
this,
"Current location:\nLatitude: " + lat + "\n"
+ "Longitude: " + lng, Toast.LENGTH_LONG).show();
// create geo point
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// get the MapController object
controller = mapview.getController();
// animate to the desired point
controller.animateTo(point);
// set the map zoom to 13
// zoom 1 is top world view
controller.setZoom(13);
// invalidate the map in order to show changes
mapview.invalidate();
drawable = this.getResources().getDrawable(R.drawable.ic_launcher);
OverlayItem overlayItem = new OverlayItem(point, "", "");
itemizedOverlay = new MyItemizedOverlay(drawable, this);
itemizedOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(itemizedOverlay);
mapview.invalidate();
} else {
System.out.println("Location not avilable");
}
// when the current location is found – stop listening for updates
// (preserves battery)
locationManager.removeUpdates(this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onLocationChanged(Location location) {
}
public MapView getMapView() {
return this.mapview;
}
}
` //here is another of item overlay
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem>
{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MyItemizedOverlay(Drawable defaultMarker, Context ctx){
super(boundCenterBottom(defaultMarker));
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void clear() {
mOverlays.clear();
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int index) {
return true;
}
}
I would recommend MyLocationOverlay.
An Overlay for drawing the user's current location (and accuracy) on the map, and/or a compass-rose inset. Subclases can override dispatchTap() to handle taps on the current location.
You will want to call enableMyLocation() and/or enableCompass(), probably from your Activity's Activity.onResume() method, to enable the features of this overlay. Remember to call the corresponding disableMyLocation() and/or disableCompass() in your Activity's Activity.onPause() method to turn off updates when in the background.
Optionally, the constructor can also take a MapController and use it to keep the "my location" dot visible by panning the map when it would go offscreen, and a View to View.postInvalidate() when location or orientation is changed.
Runnables can be provided in runOnFirstFix(java.lang.Runnable) to be run as soon as we have a fix. (For example, this could center the map and zoom in to show the location.)
You can find a good tutorial on MyLocationOverlay here

Show correct position on Google maps

I tried to implement Google positioning application to show users position on Google maps. I found this code on Stack Overflow, but the issue with this code is, it shows 500 meter or 1000 meter away from my correct position. Does anyone know how to fix it with exact location ? Any help would be highly appreciated.
This is my 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;
}
}
}
The easiest way is to use a MyLocationOverlay
https://developers.google.com/maps/documentation/android/reference/index?com/google/android/maps/MyLocationOverlay.html
Create and add to the maps overlays and it will position a marker exactly where the user is.
Something like
MyLocationOverlay myOvly = new MyLocationOverlay( this, mapView );
listOfOverlays.add( myOvly );
myOvly.enableMyLocation();
To Automatically zoom to position
myOvly.runOnFirstFix( new Runnable()
{
public void run()
{
mapController.animateTo( myOvly.getLocation() );
}
} );

How to get one or two meter accuracy for Latitude and longitude values for Current Location

getting lat,lon values one or two buildings away and not getting the exact lat and lon values.I am trying to get atleast one or two meter accuracy for Latitude and longitude values for Current Location.This is the code
public class GPSLocatorActivity extends MapActivity implements OnClickListener {
MapView mapView = null;
MapController mapController = null;
MyLocationOverlay whereAmI = null;
private Button bdiffaddr, bnext;
MyLocation myLocation;
GeoPoint p = null;
MapController mc = null;
public static LocationManager locManager;
protected ProgressDialog progressDialog;
public static double latitude, longitude;
public String TAG = "GPSLocatorActivity";
protected boolean isLocationDisplayed() {
return whereAmI.isMyLocationEnabled();
}
protected boolean isRouteDisplayed() {
return false;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpslocation);
initialiseviews();
// onclick listeners
onclicklisteners();
currentLocLatLong();
// new GoogleMapAsyncTask().execute();
GPSLocatorActivity.this.runOnUiThread(new Runnable() {
public void run() {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
whereAmI = new MyLocationOverlay(GPSLocatorActivity.this,
mapView);
mapView.getOverlays().add(whereAmI);
mapView.postInvalidate();
}
});
}
public class GoogleMapAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... voids) {
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
whereAmI = new MyLocationOverlay(GPSLocatorActivity.this, mapView);
mapView.getOverlays().add(whereAmI);
mapView.postInvalidate();
return null;
}
}
private void currentLocLatLong() {
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100L,
100.0f, locationListener);
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
Log.d("Lat: + latitude + \nLong: + longitude", "Lat:" + latitude
+ "\nLong:" + longitude);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latLongString = "Lat:" + latitude + "\nLong:" + longitude;
} else {
latLongString = "No location found";
}
}
public void onResume() {
super.onResume();
whereAmI.enableMyLocation();
whereAmI.runOnFirstFix(new Runnable() {
public void run() {
mapController.setCenter(whereAmI.getMyLocation());
}
});
}
public void onPause() {
super.onPause();
whereAmI.disableMyLocation();
}
public void onLocationChanged(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
#SuppressWarnings("unused")
String currentLocation = "Lat: " + latitude + " Lng: " + longitude;
// txted.setText(currentLocation);
p = new GeoPoint((int) latitude * 1000000,
(int) longitude * 1000000);
mc.animateTo(p);
}
}
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
please help if anyone has idea how to get the accuracy upto one or two meter distance.
Sorry, you cannot increase accuracy by programming. Accuracy increases with receiving more satellites or by using a better GPS hardware or extended systems (like WAAS using in aviation). Additionally, reception is better outside of buildings and away from any obstacles in the direct line of sight to the satellites.
To determine how many satellites you are receiving, you may look here: https://stackoverflow.com/a/8747795/1127492
BTW, 2 meters is pretty challenging. For more information on accuracy see here: http://www.gps.gov/systems/gps/performance/accuracy/#difference

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