location using GPS android - android

I am trying to determine the current geolocation, i've used the following code but i'm not getting any thing so far :
public class Activity_map extends FragmentActivity implements LocationListener {
public double latituteField;
public double longitudeField;
private GoogleMap map;
private LocationManager locationManager;
LatLng pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gmap);
loc ationManager = (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.");
onLocationChanged(location);
map.addMarker(new MarkerOptions().position(pos).title("MY POSITION").snippet("GPS")
.draggable(true));
} else {
latituteField=0;
longitudeField=0;
}
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment
= (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
map = myMapFragment.getMap();
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,5000,10,this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
pos= new LatLng(lat,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 problem is that i didn't get any marker.. i tried to do that but i had more than one marker
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
pos=new LatLng(lat,lng);
map.addMarker(new MarkerOptions().position(pos).title("MY POSITION").snippet("GPS")
.draggable(true));
}
any help will be appreciated, thank you

You havent specified any image for marker..So add it like this..
map.addMarker(new MarkerOptions().position(pos).title("MY POSITION").snippet("GPS").icon(BitmapDescriptorFactory.fromResource(R.drawable.yourmarkericon)));
and
Remove your marker from onCreate() as it is called only once at the time of activity creation..
Add your marker inside onLocationChanged() or add marker in a function and call that function inside onLocationChanged()

Related

Insert markers with different icon from my list drawable

I want to add marker on map with long click. but it is not working. normal click is working.
This is my code.
public class Map extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.map);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
// Getting GoogleMap object from the fragment
googleMap = supportMapFragment.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(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 bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
// Getting latitude of the current location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng).title("you are here" ));
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(5));
// Setting latitude and longitude in the TextView tv_location
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
public void onMapClick (LatLng point) {
// Do Something
googleMap =
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();
googleMap.addMarker(new MarkerOptions()
.position(point)
.title("TouchPoint"));
}
public void onMapLongClick(LatLng point) {
googleMap.addMarker(new MarkerOptions().position(point).title(
point.toString()));
Toast.makeText(getApplicationContext(),
"New marker added#" + point.toString(), Toast.LENGTH_LONG)
.show();
}
#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 boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
How can i solve this ?
In onCreate
googleMap.setOnMapLongClickListener(longClickListener);
Inside the activity
private OnMapLongClickListener longClickListener = new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
//do work }
}

Updating user's location

I'm having some trouble with Google Maps. I need to display user's location on the map and then update it. I'm using a default marker. However, the way my code is currently set up, it adds a new marker every time OnLocationChanged is called. I want it to just update that one marker or remove old one as it adds a new one with current location. Here's the code:
public class GoogleMapActivity extends FragmentActivity implements LocationListener {
Double longitude_user, latitude_user;
LatLng koordinate_user;
GoogleMap supportMap;
String title, address, type;
BitmapDescriptor bdf;
private LocationManager locationManager;
private String provider;
Location location;
Marker marker;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_googlemaps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMap = fm.getMap();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.GPS_PROVIDER;
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
provider = locationManager.NETWORK_PROVIDER;
}
if (provider == null){
provider = locationManager.getBestProvider(criteria, false);
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Log.i("test", "Location not available");
}
location = locationManager.getLastKnownLocation(provider);
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 1000, 10, this);
//Log.i("test", "Provider: " + provider);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
latitude_user = location.getLatitude();
longitude_user = location.getLongitude();
if (latitude_user != null && longitude_user != null) {
koordinate_user = new LatLng(latitude_user, longitude_user);
marker = supportMap.addMarker(new MarkerOptions()
.position(koordinate_user));
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Update your onLocationChanged method by this
#Override
public void onLocationChanged(Location location) {
latitude_user = location.getLatitude();
longitude_user = location.getLongitude();
if (latitude_user != null && longitude_user != null) {
if(marker != null)
marker.remove();
koordinate_user = new LatLng(latitude_user, longitude_user);
marker = supportMap.addMarker(new MarkerOptions()
.position(koordinate_user));
}
}
Hope this is what you wanted.
you can update user location onLocationchanged method....
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
if (latitude != null && longitude != null) {
if(marker != null)
marker.remove();
latlng = new LatLng(latitude, longitude);
marker = supportMap.addMarker(new MarkerOptions()
.position(latlng));
}
}

Android show location on create google maps

Good day,
at the moment I am creating an Android application that will show the user their current location on a map. Sadly I can't seem to zoom at the current location of the user in the OnCreate method. It seems to work in a OnMapClick method.
I would like to get rid of the OnMapClick method and show the current location of the user when the map is loaded.
the code below is part of the OnCreate method of the map class
Settings setting = new Settings();
setting.saveSettings(Maps.this);
LocationManager locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Here is the code of the OnLocationChanged method
public void onLocationChanged(Location location) {
int lat = (int)(location.getLatitude());
int lng =(int)(location.getLongitude());
LatLng loc = new LatLng(lat,lng);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
myMap.animateCamera(CameraUpdateFactory.zoomIn());
I posses an API key and have the map in my application.
This code may help you...
my listener
private LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location loc) {
// will get the location lat long
}
};
code to start the location manager update listener
LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager != null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String prividerName = mLocationManager.getBestProvider(criteria, true);
if (prividerName != null) {
mLocationManager.requestLocationUpdates(prividerName, 30 * 1000, 0, listener);
Once you get the lat/long u can plot the location details as below
GoogleMap googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();
LatLng current = new LatLng(mUserLatitude, mUserLongitude);
googleMap.addMarker(new MarkerOptions().position(current).title("Current Location"))
.showInfoWindow();
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current, 10));
You probably do not have a fix on the location yet. I would suggest doing
myMap.setMyLocationEnabled(true);
myMap.setOnMyLocationChangeListener(this);
then in you onLocationChanged put a boolean for a first load or something so it does not go to the location every time the location changes and then do the camera movement in there
I hope this piece of code can help to clearify my question.
the code below is my LocationListener
private LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location loc) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
}
};
the latitude and longitude ares saved in antoher class,
the code below show my way of initialzing the map.
String locLat = ((Settings)this.getApplication()).getLat();
String locLng = ((Settings) this.getApplication()).getLng();
double DlocLat = Double.parseDouble(locLat);
double DlocLng = Double.parseDouble(locLng);
myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng current = new LatLng(DlocLat,DlocLng);
myMap.addMarker(new MarkerOptions().position(current).title("Current Location")).showInfoWindow();
myMap.setMyLocationEnabled(true);//show the location on the map
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);//show the regular google maps
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current, 10));

GeoLocation identification before first change

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
I find the onLocationChanged function is PERFECTLY working when the location is Changed with the above code.
///////CLASS mylocationlistener
private class mylocationlistener implements LocationListener {
//#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
p = new GeoPoint((int)location.getLatitude(),(int)location.getLongitude());
// p = new GeoPoint((int)8.538754,(int)76.950620);
}
}
//#Override
public void onProviderDisabled(String provider) {
}
// #Override
public void onProviderEnabled(String provider) {
}
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
But the Problem is that I want the variable "p" to be filled with the current location , when the program starts, that is Before the First Change Help !!
try this code:
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) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
System.out.println("Location not avilable");
}
}
/* Request updates at startup */
#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);
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.i(TAG, "Lattitude:" +lat);
Log.i(TAG, "Longitude:" +lng);
}
Before you get fix, you can use coarse location. Check this link:
http://devdiscoveries.wordpress.com/2010/02/04/android-use-location-services/

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

Categories

Resources