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));
Related
In an app I am working on I am getting the GPS coordinates of the device inside the activity's onCreate() method. However, even after launching the app, I see the location services icon that keeps flashing in the notifications bar of the device, it this expected or should it go away after getting the position of the device?
This is my code at the moment:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_DENIED)
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
Criteria criteria = new Criteria();
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
// Get latitude and longitude
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
You are never telling LocationManager to stop providing location updates. To do that, call LocationManager.removeUpdates() with the correct listener as argument.
Alternatively, you can use LocationManager.requestSingleUpdate(...) which automatically stops providing updates after the first location.
I am trying to get my current location on map and update it when I move. Every time when an update happens, I want to get current longtidude and latitute values to use in other methods.
private LocationRequest request = LocationRequest.create().setInterval(50000);
I think I have to use LocationRequest . I created an object which will update its location every 5 minutes. But now I don't have any idea how to use it. I checked tutorials on internet but they are so complicated for a beginner. Does anybody have simple solution?
EDIT
This is how my code looks now :
public class MainActivity extends Activity implements LocationListener {
private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
getLocation();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
public void getLocation()
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
}
When I tried to test it, my app stopped working. Since this is my first android app and I am not very good at it, I couldn't find whats wrong.
for location use this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h
use gps to determine location ( longtidude and latitute values ) and pass it to maps
this mainactivity.java for gps
public class GpsBasicsAndroidExample extends Activity implements LocationListener {
private LocationManager locationManager;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_basics_android_example);
text=(TextView)findViewById(R.id.tv1);
/********** get Gps location service LocationManager object ***********/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
Parameters :
First(provider) : the name of the provider with which to register
Second(minTime) : the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
Third(minDistance) : the minimum distance interval for notifications, in meters
Fourth(listener) : a {#link LocationListener} whose onLocationChanged(Location) method will be called for each location update
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);
/********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}
/************* Called after each 3 sec **********/
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
//Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
text.setText(str);
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this for maps
main.java
enter code here
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions()
.position(CIU).title("My Office"));
final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
Marker ciu1 = mMap.addMarker(new MarkerOptions()
.position(CIU1).title("My Second Office"));
final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
Marker ciu2 = mMap.addMarker(new MarkerOptions()
.position(CIU2).title("My thired Office"));
}
}
Here is how you can do. I will try to make it simple for you:
Add LocationListener interface to your extended activity class using implements keyword. This will force you to Override some methods you will need to find your current location.
public class A extends Activity implements LocationListener {}
Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package.
private LocationManager locationManager;
Create a method like getLocation() and call the predefined service method from the Location Manger instance.
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class.
Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity.
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast.
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Last but not the least dont forget to add permissions in you Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Fore more details please refer to this link.
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()
I'm trying an application that displays the latitude and longitude positions. I tried giving lat. & lon. values using geo fix and even emulator control but I'm not getting the output. Can anyone help me out?
Here's the code and output that i get:
public class LocationTest extends Activity
{
private LocationManager mgr;
private TextView output;
private String best;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
StringBuilder sb = new StringBuilder("Enabled Provider:");
Criteria criteria = new Criteria();
String provider = mgr.getBestProvider(criteria, true);
mgr.requestLocationUpdates(provider, 1000, 0,
new LocationListener()
{
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
});
sb.append("\n").append(provider).append(":");
Location location = mgr.getLastKnownLocation(provider);
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
sb.append(lat).append(",").append(lng);
}
else
{
sb.append("No Location");
}
output.setText(sb);
}
}
Output:
Enabled provider:
gps:No Location
You need to put code in public void onLocationChanged(Location location) {} of your LocationListener. This is where location changes are informed.
getLastKnownLocation() doesn't give you current location, but last known location (which will most likely be null on the emulator).
Use Android SDK's DDMS to signal GPS position. This will call onLocationChanged(). You need a way to preserve the new location in your class (for example adding a Location class object to your Activity).
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)