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.
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.
I have an Activity that gets position with fused location and puts it in two text boxes.
In a frame, I have a Google map.
In two text boxes, I have my latitude and longitude.
I want map center to adjust as location changes.
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
latitud.setText(String.valueOf(mCurrentLocation.getLatitude()));
longitud.setText(String.valueOf(mCurrentLocation.getLongitude()));
tiempo.setText(mLastUpdateTime);
}
My idea was adding to onLocationChanged something like this:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
latitud.setText(String.valueOf(mCurrentLocation.getLatitude()));
longitud.setText(String.valueOf(mCurrentLocation.getLongitude()));
tiempo.setText(mLastUpdateTime);
LatLng mapCenter = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLatitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mapCenter, 16));
// Flat markers will rotate when the map is rotated,
// and change perspective when the map is tilted.
googleMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flecha))
.position(mapCenter)
.flat(true)
.rotation(245));
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(16)
.bearing(90)
.build();
// Animate the change in camera view over 2 seconds
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);
}
But is giving me the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
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.
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.
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