What's wrong with the below code. It is throwing Null Pointer Exception on this line (location.setLatitude(latitude);). I am trying to make a circle as soon as the application is started so that is the reason I am passing location object from my onCreate method.
private Location location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
listView = (ListView) findViewById(R.id.mylist);
mapView.setStreetView(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(15);
GeoPoint initialPoint = new GeoPoint( (int) (36.778261* 1E6), (int) (-119.417932 * 1E6));
double latitude = initialPoint .getLatitudeE6() / 1E6;
double longitude = initialPoint .getLongitudeE6() / 1E6;
location.setLatitude(latitude);
location.setLongitude(longitude);
locationListener.onLocationChanged(location);
}
Below is the class which take care of LocationUpdate.
private class GPSLocationListener implements LocationListener {
MapOverlay mapOverlay;
public GPSLocationListener(MapView mapView) {
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
mapController.animateTo(point);
mapController.setZoom(15);
if (mapOverlay == null) {
mapOverlay = new MapOverlay(this,android.R.drawable.star_on);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.add(mapOverlay);
}
mapOverlay.setPointToDraw(point);
mapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Any suggestions will be of great help.
UPDATE:-
After making changes I am getting
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
Below is my code where I made changes.
GeoPoint initialPoint = new GeoPoint( (int) (36.778261), (int) (-119.417932));
double latitude = initialPoint .getLatitudeE6() / 1E6;
double longitude = initialPoint .getLongitudeE6() / 1E6;
this.location = new Location("TechGeeky Randomly Initialized");
location.setLatitude(latitude);
location.setLongitude(longitude);
locationListener.onLocationChanged(location);
Is there anything wrong I am doing here?
I think what you want to do this is not fetch the last known location from LocationManager but instead start with a location that you defined yourself (e.g a random one) in onCreate(). To achieve this, simply create a new Location object like so:
this.location = new Location("TechGeeky Randomly Initialized");
Do this instantiation before these lines in order to avoid the Exception:
location.setLatitude(latitude);
location.setLongitude(longitude);
locationListener.onLocationChanged(location);
Intialize Location object using this code:-
If You Want get location using Mobile Network Put this code in onCreate
Location location=null;
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
If You Want get location using GPS Put this code in onCreate
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
You have instantiated location object. Where did you create object to location. Please create object to location using:
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
or
pass location object to method as argument and check null condition.
Related
I try to get my current location. First I created LocationListener:
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
myLocation = new LatLng(latitude, longitude);
}
};
The in onCreate method I try to cal requestLocatonUpates on LocationManager:
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,500f,mLocationListener);
But I get an error:
Cannot resolve method requestLocationUpdates(java.langString, long, float,com.google.android.gms.location.LocationListener)
requestLocationUpdates is a method provided in FusedLocationAPi. You should use LocationServices.FusedLocationApi.requestLocationUpdates method.
So you have to create a googleApiClient and a location request.
You can found it here : https://developer.android.com/training/location/index.html.
My objective is to track the user's location and give an alert on reaching marked location. So first I get the location to reach and marked that. Then I get the current location and compare it with marked location. But it is not working. Even I placed the marker at current location. It is not giving the toast message. Here is the code -
public class MainActivity extends FragmentActivity implements LocationListener{
LocationManager locationManager;
String provider;
ToggleButton toggle;
public static double lat,lang,value1,value2,value3,value4;
public static String strlat,strlat1;
public LatLng loc,loc1;
public double latitude,longitude;
public static String strlang,strlang1 ;
Location location;
public LocationManager locationmanager;
// Google Map
private GoogleMap googleMap;
LocationListener Locationlistener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
final Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 1000, 1, this);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
if(location!=null){
lat = location.getLatitude();
lang = location.getLongitude();
value3 =Double.parseDouble(new DecimalFormat("##.##").format(lat));
value4 =Double.parseDouble(new DecimalFormat("##.##").format(lang));
strlat = String.valueOf(value3);
strlang = String.valueOf(value4);
loc1 =new LatLng(lat, lang);
if((value1 == value3) && (value2 == value4))
{
Toast.makeText(getApplicationContext(), "target reached", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
handler.postDelayed(this, 1000);
}
};
handler.post(runnable);
}
try {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// create marker
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setOnMapClickListener(new OnMapClickListener(){
public void onMapClick(LatLng point){
Toast.makeText(getBaseContext(),
point.latitude + ", " + point.longitude,
Toast.LENGTH_LONG).show();
latitude = point.latitude;
longitude = point.longitude;
value1 =Double.parseDouble(new DecimalFormat("##.##").format(latitude));
value2 =Double.parseDouble(new DecimalFormat("##.##").format(longitude));
strlat1 = String.valueOf(value1);
strlang1 = String.valueOf(value2);
loc=new LatLng(point.latitude, point.longitude);
MarkerOptions marker = new MarkerOptions().position(loc).title("Hello Maps ");
// adding marker
googleMap.addMarker(marker);
}
});
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
/*
* creating random position around a location for testing purpose only
*/
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
There are a few things wrong in your code.
You can't compare coordinates with == because you will never have an exact match for lat/lon coordinates when tracking the device's location. You need to figure out a threshold, and if the device gets within that threshold, then show the alert.
Next, you're not using your onLocationChanged() callback, so you are just looking at the current location one time at app start-up.
Take a look at the code in my other answer here which is about determining if the device is within a circle. This is a similar problem.
So, if you were to make your threshold 10 meters, and consider the target reached if the device is within 10 meters of the target location, you would implement your onLocationChanged() method something like this:
#Override
public void onLocationChanged(Location location) {
float[] distance = new float[2];
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
latitude, longitude, distance);
if( distance[0] < 10 ){
//target location reached
Toast.makeText(getApplicationContext(), "target reached", Toast.LENGTH_SHORT).show();
}
}
one more daniel.i changed above code now it was working now have some more problem.
1.i tried to set splash screen like in my second.class.i set the above code for google map.it was running for five second while moving from one to another it get stopped
new Timer().schedule(new TimerTask(){
public void run() {
Intent intent = new Intent (MainActivity.this, SecondActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(getBaseContext(), 1000, intent, 0);
}
}, 5000);
2.i want set search in google map how to set that i tried that it not working give some idea.
I am trying to draw path from current location to destination using the answer Android: How to draw route directions google maps API V2 from current location to destination.
But in place of the hard coded I longitude and Latitude of the current location I want to use my real location. But whenever I try to do that, the App is crashing with error in line location = mMap.getMyLocation();
Any help is appreciated.
MapsActivity.Java
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
Location location;
LatLng myPosition;
GMapV2Direction md;
LatLng fromPosition = getYourLocation();
LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
md = new GMapV2Direction();
setUpMapIfNeeded();
LatLng coordinates = new LatLng(13.685400079263206, 100.537133384495975);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));
mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));
Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
/*myPosition = getLocation();
ZoomCurrentLocation(myPosition);*/
}
}
}
private LatLng getYourLocation() {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
}
LatLng latLng = new LatLng(latitude, longitude);
return latLng;
}
private void ZoomCurrentLocation(LatLng myPosition)
{
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 16));
}
private void setUpMap(LatLng myPosition) {
mMap.addMarker(new MarkerOptions().position(myPosition).title("Marker"));
}
}
Do you mean location = mMap.getMyLocation(); is the method getYourLocation() in the code, and the crash is at Location location = locationManager.getLastKnownLocation(provider); ?
If so, it may cause by NullPointer Exception, you need use new api FusedLocationApi to avoid getLastLocation null pointer.
Please check here to know how to use it. And here is the code for it on my github.
For the destination you can check here to get some idea.
I have created a method to calculate the distance from my currentposition to my hardcoded position. But it does not work. The calculator are not showing the distance. What is wrong here?
public void ourLocation()
{
myLocation = new MyLocationOverlay(this, map);
map.getOverlays().add(myLocation);
myLocation.enableMyLocation();
// Find my position
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
20000, 0, this);
controller = map.getController();
}
My onLocationChanged method.
public void onLocationChanged(Location location1) {
// Updating location and zoom
controller.setCenter(new GeoPoint(
(int) (location.getLatitude() * 1000000), (int) (location
.getLongitude() * 1000000)));
controller.setZoom(15);
Criteria crit = new Criteria();
towers = locationManager.getBestProvider(crit, false);
location = locationManager.getLastKnownLocation(towers);
//Trying to get MyPostion.
Location myLocation = new Location("point A");
myLocation.setLongitude(location.getLongitude());
myLocation.setLatitude(location.getLatitude());
Location locationB = new Location("point B");
locationB.setLatitude(55777816);
locationB.setLongitude(12533358);
float distance = myLocation.distanceTo(locationB);
//Showing the distance
AlertDialog alert = new AlertDialog.Builder(GoogleMaps.this)
.create();
alert.setTitle((int)distance);
}
By the looks of it you are receiving location updates. The Location object has functionality to calculate the distance to another location. That way you can check if you are within the radius.
i wan to ask you: i am using google Maps in my application and when i open the activity that has the map i want the user current location to be determine, i am using this code to retrieve the current user location
public void locat ()
{
//Use the LocationManager class to obtain GPS locations
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
// Class My Location Listener
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)
{
}
}// End of Class MyLocationListener */
but it is just give me the latitude and longitude and that is not what i want! i want to determine the user current location in google maps!how can i do it ? do you need my code to google MAps? Please please help me! THANK YOU
If I understand your question correctly you want to get the users current position and show it on a map. You have the latitude and longitude values, all you need to do is construct a GeoPoint and animate to that position on the map. You can also add a custom overlay to the map if desired. Something like the following should help.
double lat = location.getLatitude();
double longi = location.getLongitude();
long time = location.getTime();
GeoPoint currentGeo = new GeoPoint(toMicroDegrees(lat), toMicroDegrees(longi));
MapController controller = map.getController();
controller.animateTo(currentGeo);
You are never actually passing the information to a map in order to display the location.
What you need to do is get the MapView from the layout you displaying.
Then get the controller of the map view and set the users location as the centre/animate to their location.
Something similar to this:
mapView1 = (MapView) this.findViewById(R.id.map);
MapController mapControl = mapView1.getController();
GeoPoint geo = new GeoPoint((int)(lat)*1e6), (int(long*1e6));
mapControl.animateTo(geo);
This link should help http://mobiforge.com/developing/story/using-google-maps-android
You can open google maps with a geo uri like so:
String url = "geo:48.200927,16.369548,192";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Edit: It appears that you want reverse geocoding. Here is an example:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Here is the documentation for the android Geocoder class - http://developer.android.com/reference/android/location/Geocoder.html