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);
Related
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();
}
});
}
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;
}
}
I am new to Java and Android Studios. I am currently trying to put the MapBox map into a fragment, and obtain my device location. It kind of worked and the map launched in a fragment as well my location was found, but once I press back button on my device map crashes and app although does not turn off but become unresponsive. The logcat message I get is "2020-05-18 12:02:46.392 28026-28125/com.example.projektas5 W/libEGL: EGLNativeWindowType 0x7d2c6f4010 ". Also, I can only get my device location by allowing the permission in phone settings, since permissionsManager.requestLocationPermissions(this) only works for the activity. If anyone could help me, it would be much appreciated. My code below:
public class SecondPage extends Fragment implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
View root;
MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private LocationLayerPlugin locationLayerPlugin;
private Location originLocation;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Mapbox.getInstance(getContext(),getString(R.string.access_token));
root = inflater.inflate(R.layout.second_page, container, false);
mapView =(MapView) (root).findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return root;
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
map = mapboxMap;
enableLocation();
}
private void enableLocation() {
if (PermissionsManager.areLocationPermissionsGranted(getContext())) {
initializeLocationEngine();
initializeLocationLayer();
} else {
permissionsManager = new PermissionsManager(this);
// permissionsManager.requestLocationPermissions(this);
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(getContext()).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void initializeLocationLayer() {
locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationLayerPlugin.setLocationLayerEnabled(true);
locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),
location.getLongitude()), 13.0));
}
#Override
#SuppressWarnings("MissingPermission")
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
}
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
//Present toast or dialog. Need to do this on my own
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions,grantResults);
}
#Override
public void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.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();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationLayerPlugin != null) {
locationLayerPlugin.onStop();
}
mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
mapView.onDestroy();
}
}
It'll be helpful to use a Maps SDK SupportMapFragment
https://docs.mapbox.com/android/maps/examples/show-a-users-location-on-a-fragment/ shows how to use the Mapbox Maps SDK's LocationComponent in a SupportMapFragment.
Work off of that example? If you're still getting a crash, post more of your logcat messages. Search for anything that has Mbgl in it or search for FATAL. The "2020-05-18 12:02:46.392 28026-28125/com.example.projektas5 W/libEGL: EGLNativeWindowType 0x7d2c6f4010 ". message isn't very helpful for figuring out what went wrong when you pressed the back button.
langsmith thanks for your answer. I actually managed to find why the map was crashing for me, at the end of my code I had to add onDestroyView(), see below.
#Override
public void onDestroyView() {
super.onDestroyView();
if (locationEngine != null) {
locationEngine.deactivate();
}
// mapView.onDestroyView();
}
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);
}
}
}
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.