public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
//need this to get permission from user
public static final String ACCESS_COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
public static final String ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final int PERMISSION_REQUEST_CODE = 1234;
private LocationManager locationManager;
LatLng myGPSPosition, myNetworkPosition;
[USER=1021285]@override[/USER]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
FragmentManager fragmentManager = this.getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(map);
supportMapFragment.getMapAsync(this);
}
[USER=1021285]@override[/USER]
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getApplicationContext(), ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions();
} else {
map.setMyLocationEnabled(true);
}
try {
Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//here what you need:
double latitude = locationGPS.getLatitude();
double longitude = locationGPS.getLongitude();
//create marker
myGPSPosition = new LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myGPSPosition, 15));
//add marker
map.addMarker(new MarkerOptions()
.title("My GPS position")
.position(myGPSPosition));
}catch (NullPointerException | IllegalArgumentException e){
e.printStackTrace();
Toast.makeText(this,"Unable to get GPS data",Toast.LENGTH_SHORT).show();
}
try {
//the same, but using network proveder
Location locationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double latitude = locationNetwork.getLatitude();
double longitude = locationNetwork.getLongitude();
myNetworkPosition = new LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myNetworkPosition, 15));
map.addMarker(new MarkerOptions()
.title("My Network position")
.position(myNetworkPosition));
}catch (NullPointerException | IllegalArgumentException e){
e.printStackTrace();
Toast.makeText(this,"Unable to get Network data",Toast.LENGTH_SHORT).show();
}
}
public void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{
ACCESS_COARSE_LOCATION,
ACCESS_FINE_LOCATION
},
PERMISSION_REQUEST_CODE);
}
}