How to fix null object reference Location - java

I am having a problem with my application when trying to take my location in the onMapReady method.
I tried to take the latitude and longitude in different variables but it still comes to the onMapReady method as null.
In the Toast within the getLastLocation method it shows me my real location but when I use myLocation outside the resulting coordinates are 0.0 -0.0
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
}
Task<Location> task = fusedLocation.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
myLocation = location;
Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container, false);
fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
getLastLocation();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync( this);
return v;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
googleMap.addMarker(marker);
}
}
}
ERROR LOG:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mint, PID: 11019
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.mint.MapFragment.onMapReady(MapFragment.java:81)
at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
at android.os.Binder.transact(Binder.java:667)
at ck.b(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):14)
at com.google.android.gms.maps.internal.bb.a(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):4)
at com.google.maps.api.android.lib6.impl.bi.run(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):2)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at ln.dispatchMessage(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):5)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6672)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
I/Process: Sending signal. PID: 11019 SIG: 9
Process 11019 terminated.

your code is throwing nullPointerException because myLocation is still null so try to use below code
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
}
Task<Location> task = fusedLocation.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
myLocation = location;
//change was made here
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync( this);
Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container, false);
fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
getLastLocation();
return v;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
googleMap.addMarker(marker);
}
}
}

Related

Save the LatLng values of Marker into your database

I'm new to coding and I'm currently stuck with how to save my map markers to my SQLite database. I have an existing database for my users and passwords. I'll attach my maps activity and database helper and my edit activity which creates the markers. Any help will be appreciated.
public class MapActivity2 extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final int EDIT_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map2);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.mMap = map;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
Intent edit = new Intent(MapActivity2.this, EditActivity.class);
edit.putExtra("location", latLng);
MapActivity2.this.startActivityForResult(edit, EDIT_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (EDIT_REQUEST) : {
if (resultCode == Activity.RESULT_OK) {
MarkerOptions markerOptions = data.getParcelableExtra("marker");
mMap.addMarker(markerOptions);
}
break;
}
}
}}
This is the EditActivity which adds the marker to the map.
public class EditActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
final LatLng latlng = (LatLng) getIntent().getParcelableExtra("location");
final EditText title = (EditText) findViewById(R.id.title);
Button boton = (Button) findViewById(R.id.save);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
MarkerOptions marker = new MarkerOptions().position(latlng);
if (title.getText() != null) {
marker.title(title.getText().toString());
}
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
}

How to call activity methods or whole activity in Map Fragment

I started my first experience in coding a few days ago. Didn't find an answer for my question, so I hope someone could help me.
In my project, I have a MainActivity with a BottomNavigationView using Fragments. I added a map as one of the fragments and it works fine.
But I changed and add some methods in the MapsActivity, things like device location and ask for permission. But when I run the app it doesn't call these methods, so I think it is because the MapFragment needs to get the methods of the MapsActivity but I don't know how to solve the problem and didn't find an answer for my question.
My MapFragment
public class Map_Fragment extends Fragment implements OnMapReadyCallback {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_, container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment = SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
mapFragment.getMapAsync(this);
// Inflate the layout for this fragment
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
My MapActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
private GoogleMap mMap;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 150f;
// vars
private Boolean mLocationPermissionGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
protected void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d(TAG, "onMapReady: Map is ready");
if (mLocationPermissionGranted) {
getDeviceLocation();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d(TAG, "onCreate: Map started");
getLocationPermission();
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation : get the Devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentlocation = (Location) task.getResult();
moveCamera(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()), DEFAULT_ZOOM);
} else {
Log.d(TAG, "onComplete: current Location is null");
Toast.makeText(MapsActivity.this, "unable to find location", Toast.LENGTH_SHORT);
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d(TAG, "moveCamera: move the Camera to lat: " + latLng.latitude + ", lng" + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
private void initMap() {
Log.d(TAG, "Init Map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grandResults) {
Log.d(TAG, " onRequestPermissionResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grandResults.length > 0) {
for (int i = 0; i < grandResults.length; i++) {
if (grandResults[i] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionResult: failed");
return;
}
}
Log.d(TAG, "onRequestPermissionResult: Permission granted");
mLocationPermissionGranted = true;
//initialize our Map
initMap();
}
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
}
How I connect these two with each other that the MapFragment uses the methods of MapActivity?
If I understand your problems correctly, you want to run OnMapReadyCallback related methods from activity instead of the fragment. If this is a case, you should fix your fragment like this:
public class Map_Fragment extends Fragment {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_,container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment==null){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment=SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
Activity activity = getActivity();
if (activity != null && activity instanceof MainActivity) {
mapFragment.getMapAsync((MainActivity) activity);
}
// Inflate the layout for this fragment
return v;
}
}

Address line from google map location

I'm trying to get the address line from longitude and latitude in a text view but it never shows in the text view and the map is blank.
this is my code including the toolbar and navigation bottom and the permission:
public class Map extends AppCompatActivity {
SupportMapFragment supportMapFragment;
FusedLocationProviderClient client;
private Toolbar toolbar;
View view;
TextView textLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
client = LocationServices.getFusedLocationProviderClient(this);
textLocation = findViewById(R.id.location);
if(ActivityCompat.checkSelfPermission(Map.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
getLocation();
}else {
ActivityCompat.requestPermissions(Map.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},44);
}
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.lightGray);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView toolbar_icon = findViewById(R.id.toolbar_icon);
TextView toolbar_title = findViewById(R.id.toolbar_title);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.map);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.map:
return true;
case R.id.camera:
startActivity(new Intent(getApplicationContext()
,Camera.class));
overridePendingTransition(0, 0);
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext()
,MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.friends:
startActivity(new Intent(getApplicationContext()
,Friends.class));
overridePendingTransition(0, 0);
}
return false;
}
});
}
get the location from google map and here where I'm trying to get the line address in the textView:
private void getLocation() {
Task<Location> task = client.getLastLocation() ;
task.addOnSuccessListener((new OnSuccessListener<Location>() {
#Override
public void onSuccess(final Location location) {
if(location != null){
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions op = new MarkerOptions().position(latLng).title("IM HERE");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(op);
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
textLocation.setText(addresses.get(0).getAddressLine(0 ));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}));
}
request for permission:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 44: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
}
latitude and longitude for my current location are shown right but still, the map is blank and the address line is not shown in the TextView.

Show the Marker title, as soon as the mapbox map is loaded on android

I would like to show to user the title of the marker added to a map, however none of the solutions that i've found on the web is giving anything. Unfortunately not the showInfoWindow nor selectMarker helps:(
Please see below my code:
public class DetailAnimalPlantMapFragment extends Fragment implements OnMapReadyCallback, PermissionsListener {
private MapView mapView;
private MapboxMap mapboxMapMyLocation;
PermissionsManager permissionsManager;
List<Point> positions;
LatLng[] latLng;
LatLng myLocation;
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Mapbox.getInstance(getActivity(), getString(R.string.map_box_api));
View rootView = inflater.inflate(R.layout.fragment_ustka_object_map_mapbox, container,
false);
mapView = rootView.findViewById(R.id.mapViewMapBox);
Bundle bundle = getArguments();
Nature nature = (Nature) bundle.getSerializable("nature");
final double lat = nature.getLat();
final double lng = nature.getLng();
final String name = nature.getName();
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
if(!nature.getWaypoints().isEmpty()){
positions = PolylineUtils.decode(nature.getWaypoints(),5);
latLng = new LatLng[positions.size()];
for (int i = 0; i < positions.size(); i++) {
latLng[i] = new LatLng(
positions.get(i).latitude(),
positions.get(i).longitude());
}
mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(latLng[0]
.getLatitude(),latLng[0]
.getLongitude()))
.setTitle("Początek"));
mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(latLng[latLng.length-1]
.getLatitude(),latLng[latLng.length-1]
.getLongitude()))
.setTitle("Koniec"));
mapboxMap.addPolyline(new PolylineOptions()
.add(latLng)
.color(Color.parseColor("#38afea"))
.width(5));
}
mapboxMapMyLocation = mapboxMap;
enableLocationPlugin();
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(lat,lng))
.zoom(11)
.tilt(30)
.build();
mapboxMapMyLocation.animateCamera(CameraUpdateFactory
.newCameraPosition(position), 4000);
Marker marker = mapboxMapMyLocation.addMarker(new MarkerOptions().setPosition(new LatLng(lat,lng))
.setTitle(name));
mapboxMapMyLocation.selectMarker(marker);
/*marker.showInfoWindow(mapboxMapMyLocation,mapView);*/
}
});
return rootView;
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
DetailAnimalPlantMapFragment.this.mapboxMapMyLocation = mapboxMap;
enableLocationPlugin();
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(getActivity())) {
LocationLayerPlugin locationLayerPlugin = new LocationLayerPlugin(mapView, mapboxMapMyLocation);
// Set the plugin's camera mode
Location location = locationLayerPlugin.getLastKnownLocation();
myLocation = new LatLng(location.getLatitude(),location.getLongitude());
locationLayerPlugin.setCameraMode(CameraMode.TRACKING_GPS);
getLifecycle().addObserver(locationLayerPlugin);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(getActivity());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
}
}
As you can see I'm opening the mapView in a fragment, poiting to both the user's location and the object's location.

Get longitude and latitude

Hey guys I'm building an app and I need to get my longitude and latitude for some features I manage to get it but I can't pass it's values to my OnViewCreated method in my fragment. You can see those 2 simple toast messages in OnviewCreated they return null each time
LocatorFragment
public class LocatorFragment extends Fragment implements OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks {
private MapView mapView;
private GoogleMap map;
private GoogleApiClient mGoogleApiClient;
private Double Latitude;
private Double Longitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Intent intent = new Intent(getContext(), GPSTrackerActivity.class);
startActivityForResult(intent,1);
View v = inflater.inflate(R.layout.locator_fragment, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
Location mLastLocation;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setMyLocationButtonEnabled(false);
if (ActivityCompat.checkSelfPermission(getContext(), M anifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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 v;
}
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
// Updates the location and zoom of the MapView
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Double longitude;
Double latitude;
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
longitude = extras.getDouble("Longitude");
latitude = extras.getDouble("Latitude");
Latitude=latitude;
Longitude=longitude;
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Toast.makeText(getContext(),String.valueOf(Latitude),Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),String.valueOf(Longitude),Toast.LENGTH_SHORT).show();
};
This is my GPSTracker Activity
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
I manage to do it via following function
map = mapView.getMap();
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
Latitude= location.getLatitude();
Longitude= location.getLongitude();
Location locationzoom = map.getMyLocation();
LatLng mapCenter = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(13)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);

Categories