I want to get back the position of my phone but I have a problem with this line:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,(LocationListener) this);
I know the problem is the permission check but I don't know to do this in my code:
package com.cmn.cmnvtc;
import android.app.Fragment;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainPageFragment1 extends Fragment implements OnMapReadyCallback, LocationListener {
LocationManager locationManager;
public LatLng myLocation;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,(LocationListener) this);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(48.9818555, 2.270541);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 15));
googleMap.addMarker(new MarkerOptions().title("Le garage").position(marker));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
public void onLocationChanged(Location location) {
if(location != null){
Toast.makeText(getActivity(), "Latitude:" + location.getLatitude() + " - Longitude:" + location.getLongitude(), Toast.LENGTH_SHORT);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
How can I do this , please?
My error is in the code : "Add permission check"
You need to check it for Marshmollow
private static final int GRANTED = PackageManager.PERMISSION_GRANTED;
if (checkCoarseLocationPermission(getActivity()) && checkFineLocationPermission(getActivity())) {
//permissions are granted
}else {
requestLocationPermission(getActivity());
}
}
public boolean checkCoarseLocationPermission(Activity mActivity){
int permissionCheck = ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionCheck == GRANTED;
}
public boolean checkFineLocationPermission(Activity mActivity){
int permissionCheck = ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionCheck == GRANTED;
}
public void requestLocationPermission(Activity mActivity){
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
try this
public void onLocationChanged(Location location) {
if(location != null){
location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(getActivity(), "Latitude:" + location.getLatitude() + " - Longitude:" + location.getLongitude(), Toast.LENGTH_SHORT);
}
}
You need to add the permissions in the manifest of your app. Open your manifest.xml and put this two lines:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
ACCESS_FINE_LOCATION allows your app to track the user position using the actual GPS.
ACCESS_COARSE_LOCATION allows your app to track the user position using WiFi Networks, so you can omit this one if you are only using the GPS.
Related
I want to find out where my location is currently on the device connected to my computer, but since my location has not changed, it does not fall into the onLocationChanged function and therefore returns location = null. How do I enter the onLocationChanged function?
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Like Sai suggested, you can use the fused location provider to retrieve the device's last known location which will display your current location.
Check out the working code sample below:
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private FusedLocationProviderClient fusedLocationClient;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (checkPermissions()) {
mMap.setMyLocationEnabled(true);
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
System.out.println("current location: " + location.toString());
} else {
System.out.println("current location is null");
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
System.out.println("error trying to get current location");
e.printStackTrace();
}
});
}
private boolean checkPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
requestPermissions();
return false;
}
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
}
Hope it helps!
I am trying to write an app which constantly monitors the speed at which I run and tells me to speed up if I am running slow and vice verse. My code has no errors, but my TextView text doesn't change as it's supposed to as per my code. Please take a look at my mainActivity.java code:
package com.example.kaushik.speed_measurement;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextToSpeech toSpeech;
int status;
String text;
String text1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
this.onLocationChanged(null);
toSpeech=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener(){
#Override
public void onInit(int i) {
if ( status ==TextToSpeech.SUCCESS) {
toSpeech.setLanguage(Locale.UK);
}
else{
Toast.makeText(getApplicationContext(), "Feature not supported",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void onLocationChanged(Location location) {
TextView txt = (TextView) this.findViewById(R.id.speed);
if (location==null){
txt.setText("-,- m/s");
}
else{
float nCurrentSpeed=location.getSpeed();
txt.setText(nCurrentSpeed + "m/s");
if (nCurrentSpeed<5) {
TextView txt1 = (TextView) this.findViewById(R.id.message);
txt.setText("Speed up!");
text = ("Speed up");
toSpeech.speak(text, TextToSpeech.QUEUE_FLUSH,null);
}
else{
TextView txt1 = (TextView) this.findViewById(R.id.message);
txt1.setText("Slow down");
text1 = ("Slow down");
toSpeech.speak(text1, TextToSpeech.QUEUE_FLUSH,null);
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
im writing android navigation app using geolocation but i have problem with frequency updating location.
picture
i get response in log.d() after approx 20 seconds. Im afraid its too slow for example when i use it while driving. The assumption is that the Marker should move smoothly.
NavigationActivity class:
package com.nowinski.kamil.drivertool;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import utils.LatLngInterpolator;
import utils.MarkerAnimation;
public class NavigationActivity extends FragmentActivity implements
OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
private PlaceAutocompleteFragment placeAutocompleteFragment;
private Marker marker;
private Marker markerCurrentLocation = null;
private final float ZOOM = 12.2f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//initialize placeAutocompleteFragment and set on listener
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if(marker!=null){
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(NavigationActivity.this, ""+status.toString(), Toast.LENGTH_SHORT).show();
}
});
//check permissions
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
//initialize locationManager to get the location system service
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
private void updateMarkerPosition(Location newLocation){
//test
Log.d("locationChanged", Double.toString(newLocation.getLatitude())+" "+Double.toString(newLocation.getLongitude()));
LatLng newLatLng = new LatLng(newLocation.getLatitude(), newLocation.getLongitude());
//if marker used first time addMarker to map and move camera
if(markerCurrentLocation == null){
markerCurrentLocation = mMap.addMarker(new MarkerOptions().position(newLatLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
} else {
MarkerAnimation.animateMarkerToICS(markerCurrentLocation, newLatLng, new LatLngInterpolator.Spherical());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
this.location = location;
updateMarkerPosition(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
//activity life cycle
#Override
protected void onDestroy(){
super.onDestroy();
//stop GPS
locationManager.removeUpdates(this);
}
}
There are detected activities when user is walking or driving or running. Google doc.
But i suggest you implement this by using these well tested and maintained libraries like
1.https://github.com/akexorcist/Android-GoogleDirectionLibrary
2.https://github.com/jd-alexander/Google-Directions-Android
Which provide you many in library functions to use. and you will need not to RnD on everything of location listening.
My current goal is to send the LatLng to Firebase. I did achieve this but the problem I have now is that after a couple of updates to Firebase, my location field starts to receive updates super fast which in turn lags my application and also increases my phones temperature.
How would I go about sending location updates to firebase twice every minute without having the application lag?
I send the location updates to Firebase under the onLocationChanged(Location) method.
Here is my Mapfragment class.
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.mycompany.neighbors.MainActivity;
import com.mycompany.neighbors.R;
import com.mycompany.neighbors.User;
/**
* Created by joshua on 5/25/2016.
*/
public class MapFragment extends Fragment implements OnMapReadyCallback,LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
private final String FIREBASE_URL = "MY_URL";
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
SupportMapFragment mSupportMapFragment;
private GoogleMap maps;
private boolean permissionIsGranted = false;
private LatLng mLatLng;
private User mApplicationUser;
private static String mApplicationUserUID;
public static MapFragment newInstance(int index){
MapFragment mapFragment = new MapFragment();
Bundle args = new Bundle();
args.putInt("index",index);
mapFragment.setArguments(args);
return mapFragment;
}
private void createMap(){
mSupportMapFragment = SupportMapFragment.newInstance();
FragmentManager fm = getFragmentManager();
mSupportMapFragment.getMapAsync(this);
if(!mSupportMapFragment.isAdded())
fm.beginTransaction().add(R.id.map_frag,mSupportMapFragment).commit();
else if(mSupportMapFragment.isAdded())
fm.beginTransaction().hide(mSupportMapFragment).commit();
else
fm.beginTransaction().show(mSupportMapFragment).commit();
}
private void requestLocationUpdates() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(60000);
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
/////////////////////////////////////////OVERRIDE METHODS////////////////////////////////////////////////////////////
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_map,container,false);
mApplicationUserUID = MainActivity.getUID();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
createMap();
return v;
}
////////////////////////////////////////LIFECYCLE METHODS///////////////////////////////////////////////////////////
#Override
public void onStart(){
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume(){
super.onResume();
if(permissionIsGranted){
if(mGoogleApiClient.isConnected()){
requestLocationUpdates();
}
}
}
#Override
public void onStop(){
if(permissionIsGranted){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
mGoogleApiClient.disconnect();
}
super.onStop();
}
///////////////////////LIFECYCLE METHODS//////////////////////////////////////////////
#Override
public void onMapReady(GoogleMap googleMap) {
maps = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("TAG_JOSH", "onConnected");
requestLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
Log.d("TAG_JOSH", "Connection suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d("TAG_JOSH", "Connection failed");
}
#Override
public void onLocationChanged(final Location location) {
Log.d("TAG_JOSH","Latitude: " +Double.toString(location.getLatitude()));
final LatLng coordinates = new LatLng(location.getLatitude(),location.getLongitude());
final Firebase userRef = new Firebase("MY_URL");
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userRef.setValue(coordinates);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
switch(requestCode){
case MY_PERMISSIONS_REQUEST_FINE_LOCATION:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission granted
permissionIsGranted = true;
} else{
//Permission denied
permissionIsGranted = false;
Toast.makeText(getContext(),"This app requires location permissions", Toast.LENGTH_SHORT).show();
}
break;
}
}
/////////////////////////////////////////OVERRIDE METHODS////////////////////////////////////////////////////////////
}
If you're trying to send your location twice a minute, you need to remove the part of sending location updates in Firebase inside onLocationChanged.
Add a CountDownTimer and trigger to send a location update after each 30 seconds have passed.
So you need to do something like this.
Take two global variables
private Location currentLocation;
private Location previousLocation;
Now inside your onCreateView declare a timer like this.
new CountDownTimer(30000, 1000) { // 30 seconds timer
public void onTick(long millisUntilFinished) {
// Do nothing
}
public void onFinish() {
// Send location update to firebase here if the previous location sent to server and the current location is not the same.
final LatLng coordinates = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
if(currentLocation == previousLocation) return; // Pseudo code
final Firebase userRef = new Firebase("MY_URL");
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userRef.setValue(coordinates);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
// Now start the timer from here again.
this.start(); // Pseudo code.
}
}.start();
Inside your onLocationChanged function, just update the currentLocation like this
#Override
public void onLocationChanged(final Location location) {
currentLocation = location; // Update the current location here
}
this is my code of current location. i'm new to android so can anyone help me out ?
i need to send the current location to server and update it i certain time interval so that the user can fetch the location and display it on the map.it is basically a tracking device.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity 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.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
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);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#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
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}