I have a problem with obtaining the current user location. Code at first works but after some time it just stops showing the current location. I tried several approaches to this problem but with the same result.
Here's my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapscreen);
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
String provider = getProvider();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//getLastKnownPoint();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
drawCurrPositionOverlay();
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
GeoPoint currentPoint = getCurrentPoint(location);
animateToCurrentPoint(currentPoint);
currentLocation = location;
currentGeoPoint = currentPoint;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public GeoPoint getCurrentPoint (Location location){
GeoPoint currentPoint = new GeoPoint((int)(location.getLatitude()*1E6),(int)(location.getLongitude()*1E6));
return currentPoint;
}
public GeoPoint getLastKnownPoint (){
GeoPoint lastKnownPoint = null;
Location lastKnownLocation = locationManager.getLastKnownLocation(getProvider());
if(lastKnownLocation != null){
lastKnownPoint = getCurrentPoint(lastKnownLocation);
}
return lastKnownPoint;
}
public void animateToCurrentPoint(GeoPoint currentPoint){
mapController.animateTo(currentPoint);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
}
public void drawCurrPositionOverlay(){
List<Overlay> overlays = mapView.getOverlays();
CustomItemizedOverlay<CustomOverlayItem> itemizedOverlay;
overlays.remove(currPos);
Drawable marker = getResources().getDrawable(R.drawable.me);
currPos = new MapOverlay(marker,mapView);
GeoPoint drawMyPoint = null;
if(currentGeoPoint==null){
drawMyPoint = getLastKnownPoint();
}
else {
drawMyPoint = currentGeoPoint;
}
OverlayItem overlayitem = new OverlayItem(drawMyPoint, "I'm here ", "wee");
currPos.addOverlay(overlayitem);
overlays.add(currPos);
currPos.setCurrentLocation(currentLocation);
}
public String getProvider() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String Provider = locationManager.getBestProvider(criteria, true);
return Provider;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(getProvider(), 100, 1, locationListener);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
}
And I also had a problem with the drawCurrPosition (when code "was working") function (which uses custom balloons), method put a marker on the last known location, not on my current location (so marker was always one step back).
Function put the marker on the current location only on the opening app.
Please can you help me as I can't see what's wrong with my code
drawCurrPositionOverlay() is called in onCreate() and should really just be called in the onLocationChanged(). That way your overlay is always being updated with the current location instead of containing just the first location.
Related
i am trying to get location from both network provider and gps.By using the returned latitude and longitude i am placing markers on map. When i tried with network provider app is working fine.But when i tried to get location from gps, for the first time it is returning null. After that it is giving me exact location result. How to get rid from this.?
I think some minor changes i have to made, please suggest me in fixing this.
this is how i am doing this.
public class MapActivity extends Activity implements LocationListener {
private GoogleMap gMap;
private LocationManager locationManager;
private String provider;
boolean gps_enabled = false;
boolean netwrk_enabled = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
//Focussing india on starting map
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
23.40276491, 77.51953125), 5));
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
netwrk_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps_enabled)
provider = LocationManager.GPS_PROVIDER;
else
provider = LocationManager.NETWORK_PROVIDER;
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
CameraPosition cp = new CameraPosition(new LatLng(
location.getLatitude(), location.getLongitude()), 14, 40, 90);
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp), 4000,
null);
gMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude()))
.title("I am here"));
if (location != null) {
if (provider == LocationManager.GPS_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from gps",
Toast.LENGTH_SHORT).show();
else if (provider == LocationManager.NETWORK_PROVIDER)
Toast.makeText(getApplicationContext(), "taking from network",
Toast.LENGTH_SHORT).show();
new HttpGetTask().execute();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub18d1:d002
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private class HttpGetTask extends AsyncTask<Void, Void, String> {
//Passing latitude and longitude here to get lat longs from my remote server.
// using json parsing i am placing multiple markers here.
}
}
Everything you code is write, But you are not calling LocationManager on starting of Application. Just un comment the following line from your code from your onCreate() method.
//Location location = locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 10F, this);
Uncomment above line and make following change for provider
Location location = locationManager.requestLocationUpdates(provider, 5000L, 10F, this);
I have an app which calculates distance and speed by gps
the speed is working well
but the distance always equals to zero !!
at first i didn't initialize float[] dist by zero .. but it crashed once gps was found !
that's the code
public class Main_Activity extends Activity {
TextView tvdistance;
TextView tvSpeed;
double currentLon = 0;
double currentLat = 0;
double lastLon = 0;
double lastLat = 0;
double distance = 0;
float[] dist = {
0, 0, 0
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
tvdistance = (TextView) findViewById(R.id.tvdistance);
tvSpeed = (TextView) findViewById(R.id.tvspeed1);
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
tvdistance.setText("No GPS location found");
}
else {
// set Current latitude and longitude
currentLon = loc.getLongitude();
currentLat = loc.getLatitude();
}
// Set the last latitude and longitude
lastLat = currentLat;
lastLon = currentLon;
}
LocationListener Loclist = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// start location manager
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get last location
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Request new location
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
// Get new location
Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// get the current lat and long
currentLat = loc.getLatitude();
currentLon = loc.getLongitude();
if (currentLat != 0 && currentLon != 0) {
Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
location.getLongitude(), dist);
distance += (long) dist[0];
}
currentLat = location.getLatitude();
currentLon = location.getLongitude();
float speed = location.getSpeed();
tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
tvdistance.setText("Distance = " + distance);
}
#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
}
};
}
As you have just gotten a location fix, I fully expect the location returned from getLastKnownLocation to be the same as what you get in location. This means that your distance between the two is correctly 0. If you want your older location, you'll need to store that yourself.
Here is the complete code to get location updates from a GPS provider
public class MainActivity extends Activity {
private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
// meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
// second
// Declaring a Location Manager
protected LocationManager locationManager;
// The alert dialog to enable GPS
private Dialog alertDialog;
// flag for GPS status
boolean isGPSEnabled = false;
Location location; // location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onStart()
*/
#Override
protected void onStart() {
// fetching your current location
super.onStart();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
if (googleMap != null) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
// Getting current location and adding the marker
locateMe();
}
/**
*
*/
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
/*
* (non-Javadoc)
*
* #see android.app.Activity#onResume()
*/
#Override
protected void onResume() {
// Getting location from GPS
super.onResume();
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.e("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
}
Now you can use various methods to store your location. Following are some ways:
Shared preferences
SQLite Database
Web Server
Saving in a file
You can refer this link.
i am developing one application in that i want to show my current location in the map,it shows but if i change location its shows previous location please tell me in my code mistake
my code
public class GetLatLongForTPActivity extends FragmentActivity implements LocationListener{
GoogleMap _googleMap;
static final LatLng SEC = new LatLng(17.433189,78.502223);
static final LatLng Safilguda = new LatLng(17.464166,78.536156);
static final LatLng Fathe = new LatLng(17.455932,78.450132);
LatLng myPosition;
LatLongDetails latLongDetails = new LatLongDetails();;
private EditText timeEdit;
private Button submitBtn;
private Button cancelBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
/*Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
*/
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
Log.e(" NEW LATLONG1",arl.get(0).toString());
Log.e(" NEW LATLONG2",arl.get(1).toString());
Log.e(" NEW LATLONG3",arl.get(2).toString());
_googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
if(_googleMap==null){
Toast.makeText(getApplicationContext(), "Google Map Not Available", Toast.LENGTH_LONG).show();
}
LocationManager locationManger = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria=new Criteria();
Marker perth = _googleMap.addMarker(new MarkerOptions()
.position(SEC)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
/*Marker Safilg = _googleMap.addMarker(new MarkerOptions()
.position(Safilguda)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));
Marker Saf = _googleMap.addMarker(new MarkerOptions()
.position(Fathe)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true));*/
String provider = locationManger.getBestProvider(criteria, true);
Location location = locationManger.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
latLongDetails.setLat(latitude);
latLongDetails.setLongi(langitude);
Log.e("lat",""+ latLongDetails.getLat());
Log.e("long", ""+latLongDetails.getLongi());
LatLng latlang = new LatLng(latitude, langitude);
LatLngBounds curScreen = _googleMap.getProjection().getVisibleRegion().latLngBounds;
curScreen.contains(latlang);
myPosition = new LatLng(latitude, langitude);
_googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
_googleMap.addMarker(new MarkerOptions().position(myPosition).title("start"));
//_googleMap.setOnMarkerClickListener(GetLatLongForTPActivity.this);
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String
clreatime=timeEdit.getText().toString().trim();
latLongDetails.setClearTime(clreatime);
Log.e("time",
latLongDetails.getClearTime());
new
SendLatLongValAsync(GetLatLongForTPActivity.this).execute(latLongDetails);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
Setup your Activity like below:
public class BasicMapActivity_new extends FragmentActivity implements LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private String provider;
Double Latitude,longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2)).getMap();
mMap.setMyLocationEnabled(true);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!enabledGPS) {
Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
else if(!enabledWiFi){
Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
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, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
onLocationChanged(location);
} else {
//do something
}
setUpMap();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map2))
.getMap();
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
}
Marker startPerc=null;
Location old_one;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng)
startPerc = mMap.addMarker(new MarkerOptions()
.position(coordinate)
.title("Current Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f))
}
#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
}
}
And do not forget to add permission into manifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You have used getLastKnownLocation() method while fetching the location details. This method always returns the last know co-ordinates. So, I suggest you to commenting this line Location location = locationManger.getLastKnownLocation(provider); from your code. Then it will run properly.
To update your location you have to register your Location Listener to location manager. And use override method onLocationChanged() to get latest location.
Please refer http://developer.android.com/guide/topics/location/strategies.html
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
I have followed the HelloMapView tutorial for android, and added some code to capture my current location information and display in a textview.
I have tested these code in another program and it worked, it is able to display my longitude and latitude data when the launch that app. However when i copied the code into this MapActivity, it seems that i cannot get the location data.
Here's part of the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new HelloItemizedOverlay(drawable, this);
Button button1 = (Button)this.findViewById(R.id.button1);
tv1 = (TextView) this.findViewById(R.id.textView1);
button1.setOnClickListener(mScan);
latitude = 1.3831625;
longitude = 103.7727321;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (System.currentTimeMillis() - location.getTime() < 3000)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(longitude));
}
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(latitude));
}
#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
}
};
Did you added proper permissions in Manifest? Like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Also please check your gps is enabled or working on ur deive.