mock location in android - 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.

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

Android map with different location with different marker image

I'm doing map application in android.For that,i need to show current location with one marker image.And when i type any address on top editText box,i need to show tht location with different marker image + i can change that second marker into tapped locations.For me,initially it shows current location with one marker well.But when i type.,while second marker has come.,that first marker(current location) will disapper.I want to have both two markers on view.How could i do that?
My code:
Handler h = new Handler() {
// Invoked by the method onTap()
// in the class CurrentLocationOverlay
#Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
// Getting the Latitude of the location
int latitude = data.getInt("latitude");
// Getting the Longitude of the location
int longitude = data.getInt("longitude");
// Show the location in the Google Map
showLocation(latitude, longitude);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to map_view available in activity_main.xml
mapView = (MapView) findViewById(R.id.map_view);
// Getting reference to tv_location available in activity_main.xml
tvLocation = (TextView) findViewById(R.id.tv_location);
initLocationManager();
// Default Latitude
int latitude = 28426365;
// Default Longitude
int longitude = 77320393;
// Show the location in the Google Map
showLocation(latitude, longitude);
}
private void initLocationManager() {
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:" + longitude);
// Creating an instance of GeoPoint corresponding to latitude and
// longitude
GeoPoint point = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable = this.getResources().getDrawable(
R.drawable.ic_launcher);
// Creating an instance of ItemizedOverlay to mark the current location
// in the map
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(
drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point,
"Current Location", "Latitude : " + latitude + ", Longitude:"
+ longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
#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
}
private void showLocation(int latitude, int longitude) {
// Setting Latitude and Longitude in TextView
tvLocation.setText("Latitude:" + latitude / 1e6 + "," + "Longitude:"
+ longitude / 1e6);
// Setting Zoom Controls
mapView.setBuiltInZoomControls(true);
// Getting the MapController
MapController mapController = mapView.getController();
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.marker);
// Creating an ItemizedOverlay
TouchedLocationOverlay locationOverlay = new TouchedLocationOverlay(
drawable, h);
// Getting the MapController
MapController mc = mapView.getController();
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint(latitude, longitude);
// Locating the point in the Google Map
mc.animateTo(p);
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Item", "Item");
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Clearing the overlays
overlays.clear();
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Redraws the map
mapView.invalidate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return false;
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker, double lat, double lang) {
super(marker);
boundCenterBottom(marker);
items.add(new OverlayItem(getPoint(lat, lang), "", ""));
populate();
}
public SitesOverlay(Drawable marker, double[] latitude,
double[] longitude) {
super(marker);
// boundCenterBottom(marker);
for (int i = 0; i < latitude.length; i++) {
items.add(new OverlayItem(getPoint(latitude[i], longitude[i]),
"", ""));
}
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
/*
* Toast.makeText(LocationBasedServicesV2.this,
* items.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
*/
return (true);
}
#Override
public int size() {
return (items.size());
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
TochedLocation:
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Handler handler;
public TouchedLocationOverlay(Drawable defaultMarker,Handler h) {
super(boundCenterBottom(defaultMarker));
// Handler object instantiated in the class MainActivity
this.handler = h;
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Invokes the method createItem()
}
// This method is invoked, when user tap on the map
#Override
public boolean onTap(GeoPoint p, MapView map) {
List<Overlay> overlays = map.getOverlays();
// Creating a Message object to send to Handler
Message message = new Message();
// Creating a Bundle object ot set in Message object
Bundle data = new Bundle();
// Setting latitude in Bundle object
data.putInt("latitude", p.getLatitudeE6());
// Setting longitude in the Bundle object
data.putInt("longitude", p.getLongitudeE6());
// Setting the Bundle object in the Message object
message.setData(data);
// Sending Message object to handler
handler.sendMessage(message);
return super.onTap(p, map);
}
Thanks.
If you want the first overlay to be fixed which is your current location overlay, try with the below code and let me know.
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.remove(1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();
or
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
if(listOfOverlays.size() > 1)
listOfOverlays.remove(listOfOverlays.size()-1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();

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

Categories

Resources