Latitude value set to 0 - android

I set a value from MainActivity to Fragment, but the value become 0 in Fragment.
when I got log in moveToLocation(), value of latitude was 0, but when I got log in setLocation, value of latitude was correct passed value.
why is this?
MainActivity
MapFragment mapFragment = new MapFragment();
mapFragment.setLocation(111, 222, "abcAddress");
Fragment
public class MapFragment extends Fragment {
private GoogleMap mMap;
private double mLatitude;
private double mLongitude;
private String mAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Log.d("", "You must update Google Maps.");
getActivity().finish();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
moveToLocation();
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.map_page, null);
}
public void setLocation(double latitude, double longitude, String address) {
mLatitude = latitude;
mLongitude = longitude;
mAddress = address;
}
protected void moveToLocation() {
CameraPosition location = new CameraPosition.Builder()
.target(new LatLng(mLatitude, mLongitude)).zoom(15.5f)
.bearing(0).tilt(25).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(location));
MarkerOptions marker = new MarkerOptions().position(new LatLng(mLatitude, mLongitude)).title(mAddress);
marker.snippet("Snippet");
mMap.addMarker(marker);
}
}

You should not create the new instance of MapFragment.
To pass the values, set them in Argument while adding them in the Transaction :
Bundle bundle = new Bundle();
bundle.putDouble("lat", latitude);
bundle.putDouble("long", longitude);
bundle.putString("address", address);
myFragment.setArguments(bundle);
And fetch the value in onCreate() like :
#Override
public View onCreate(Bundle savedInstanceState) {
Bundle mBundle = getArguments();
if (mBundle != null) {
String address = mBundle.getString("address");
// Call method
setLocation(mBundle.getDouble("lat"), mBundle.getDouble("long"), mBundle.getString("address"));
} else {
Toast.makeText(getActivity(), "Location Not Found", Toast.LENGTH_SHORT).show();
}
}
Hope it helps ツ

Related

get last known location in android [duplicate]

This question already has answers here:
Location is empty at the start
(5 answers)
Closed 3 years ago.
This topic is populated in SO, but due to my limited knowledge in java, I am unable to get my location.
If I manually put latitude and longitude, my code is working as expected. I use this to put the latitude and longitude hardcoded:
class latlang {
public static double Lat=28.28;
public static double Lang=84.0;
}
which is used in other fragments, as, but not only in map:
MapFragment.java
public class MapFragment extends Fragment {
private MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(mMap -> {
googleMap = mMap;
LatLng sydney = new LatLng(latlang.Lat, latlang.Lang);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Kindly help. I am totally confused with FusedLocationProviderClient
main_activity.java
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
//new SecondFragment();
//TabLayout tabs = findViewById(R.id.tabs);
//tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
FontDrawable drawable = new FontDrawable(this, R.string.fa_plus_solid, true, false);
drawable.setTextColor(ContextCompat.getColor(this, android.R.color.white));
fab.setImageDrawable(drawable);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Check permission
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
}
First you need to initialize the fusedLocationClient like this :
In Fragment:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
In Activity:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
then to retrieve last known location :
fusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations, this can be null.
if (location != null) {
// Logic to handle location object
double latitude= location.getLatitude();
double longitude= location.getLongitude();
} else {
//handle null location
}
}
});
Hope this helps!

Communication between two Activities?

I'm making an app in which I'm using GoogleMaps.Now, I have a question about communication between MapActivity and ToursActivity.To simplify it, my app is about band Metallica, and I have list of Tours. When user clicks on one of the Tours, it should open a new Activity with that location. I won't put ToursActivity here, cause there is a bunch of code that you don't need.Also, I'm keeping all my data on Firebase, if that's important.
This is my MapActivity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;
private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
#BindView(R.id.lvTours) ListView lvTours;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tours_coord);
this.initialize();
lvTours.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
public void initialize(){
this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
this.mMapFragment.getMapAsync(this);
this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
MarkerOptions newMarkerOptions = new MarkerOptions();
newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
newMarkerOptions.title("Tour");
newMarkerOptions.snippet("It' was here!");
newMarkerOptions.position(latLng);
mGoogleMap.addMarker(newMarkerOptions);
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.mGoogleMap = googleMap;
UiSettings uiSettings = this.mGoogleMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setZoomGesturesEnabled(true);
this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
goToLocation(33.835293 , -117.914505);
}
public void goToLocation(double lat, double lng){
LatLng latLng = new LatLng(lat, lng);
CameraPosition position = CameraPosition.builder()
.target(latLng)
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position),null);
}
private boolean hasLocationPermission() {
String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int status = ContextCompat.checkSelfPermission(this, LocationPermission);
if (status == PackageManager.PERMISSION_GRANTED) {
this.mGoogleMap.setMyLocationEnabled(true);
return true;
}
return false;
}
private void requestPermission() {
String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}
}
You can use Intent with extra parameters.
For example, on ToursActivity.java
Intent intent = new Intent(ToursActivity.this, MapActivity.class);
intent.putExtra("lat", latitude);
intent.putExtra("long", longitude);
startActivity(intent);
Then you can get get these parameters on onCreate() method of MapActivity.java:
Intent intent = getIntent();
long latitude = intent.getLongExtra("lat", 0);
long longitutde = intent.getLongExtra("long", 0);
You can use intent with extra parameters.
Intent intent = new Intent(ToursActivity.this, MapActivity.class);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
startActivity(intent);
Then you can get your values in onCreate() method of MapActivity.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
double latitude = intent.getDouble("latitude");
double longitude = intent.getDouble("longitude");

Navigation Drawer unable to take to specific location in maps fragment in android

OK, so i have a map in a fragment and a navigation drawer in my app. The map loads when the app is run and points to the current location. Now I have added few places in my navigation list with their lats and longs. Now all i want to do is whenever i click one of such places in my navigation drawer it takes me to that place without loading the map fragment again and also without changing the current set markers on the map.
Here's the SelectItem method which is called on each item click in the navigation drawer. This method exists in the MainActivity of my application
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
fragment = new MAPFragment();
Log.e("In main activity","Lets see what happens");
String[] coords = dataList.get(possition).getGeo().split(",");
Double c1 = new Double(Double.valueOf(coords[0]));
Double c2 = new Double(Double.valueOf(coords[1]));
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
final Fragment existingFragment = frgManager.findFragmentById(R.id.map);
if(existingFragment !=null){
((receiveData)existingFragment).navigateToNewLocation(c1,c2);
}
else
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
Here's my map fragment...
interface receiveData{
public void navigateToNewLocation(double lat, double lon);}
public class MAPFragment extends Fragment implements receiveData {
public String IMAGE_RESOURCE_ID = "iconResourceID";
public String ITEM_NAME = "itemName";
public String GEO = "39.933333,32.866667";
public void setParameters(double lat, double lon){
navigateToNewLocation(lat, lon);
}
// Google Map
private GoogleMap googleMap;
ImageView ivIcon;
TextView tvItemName;
MapView mapView;
String[] coords = GEO.split(",");
Double c1 = new Double(Double.valueOf(coords[0]));
Double c2 = new Double(Double.valueOf(coords[1]));
public MAPFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container,
false);
Log.e("coords[0]",coords[0]);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
/**
* function to load map. If map is not created it will create it for you
* */
public void initilizeMap() {
if (googleMap==null){
googleMap=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.setMyLocationEnabled(true);
Log.e("In MAPFragment","Before coords!=null");
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(c1,c2)));
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
}
});
//checking
if(googleMap==null){
Toast.makeText(getActivity().getApplicationContext(), "Unable to create", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// 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
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onDestroyView()
{
super.onDestroy();
mapView.onDestroy();
}
public void navigateToNewLocation(double lat, double lon){
Log.e("INSIDE navigateToNewLoc","next is cam pos");
// On clicking a user
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(lat,lon)).zoom(12).build();
Log.e("INSIDE navigateToNewLoc","next is animateCam");
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
Right now with these code everytime i click on an item in navigation drawer, the app fails....i guess this happens because of the Class Cast Exception in this very line in SelectItem method
((receiveData)existingFragment).navigateToNewLocation(c1,c2);
Here's my log cat
09-10 03:00:00.784: E/AndroidRuntime(31030): FATAL EXCEPTION: main
09-10 03:00:00.784: E/AndroidRuntime(31030): Process: com.findmeWithdrawer, PID: 31030
09-10 03:00:00.784: E/AndroidRuntime(31030): java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to com.findmeWithdrawer.receiveData
09-10 03:00:00.784: E/AndroidRuntime(31030): at com.findmeWithdrawer.MainActivity.SelectItem(MainActivity.java:205)
Before you create your fragment, try to query first if it already exists. For example:
final Fragment existingFragment = fragmentManager.findFragmentByTag("myfragmentname");
If it doesn't exists then:
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment,"myfragmentname")
.commit();
Then, pass your parameters to your fragment (whether newly instantiated or not) by implementing a method for receiving parameters (implement an interface):
((SomeInterface)existingFragment).SetParameters(blah1, blah2, blah3);
Your fragment definition implements this interface
public class MAPFragment extends Fragment implements SomeInterface {
public SetParameters(int blah1, int blah2, int blah3) {
// do your stuff here...

java.lang.NullPointerException: CameraUpdateFactory is not initialized logcat exception

I'm working with Google Maps. I am able to successfully create and can show a Google Map. Now I want to add CameraUpdate(latitude, longitude). I googled and I found some source code but I'm getting a NullPointerException.
The LogCat error message is:
java.lang.NullPointerException: CameraUpdateFactory is not initialized
This is my source. What am I doing wrong?
public class StradaContact extends Fragment {
public final static String TAG = StradaContact.class.getSimpleName();
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
double longitude = 44.79299800000001, latitude = 41.709981;
public StradaContact() {
}
public static StradaContact newInstance() {
return new StradaContact();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_contact, container,false);
mMapView = (MapView) rootView.findViewById(R.id.pointMap);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(rootView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.pointMap)).getMap();
if (mMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
<com.google.android.gms.maps.MapView
android:id="#+id/pointMap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
Try this in "onCreate":
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
Try with following method initialize google map api before using
MapsInitializer.initialize(getActivity());

Google Maps only shows one marker Android

I've the next problem, I'm trying to show some markers in a Google Map, but only show the first marker, not the others. It don't throw any exception, but only shows the first marker (the phone position).
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
v = inflater.inflate(R.layout.fragment_map, container, false);
Bundle b = getArguments();
receiveExtraData(b);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) v.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(v);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (FragmentsListener) activity;
} catch (ClassCastException e) {}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
GPSPoint point = new GPSPoint(context);
LatLng latLng = point.getCurrentPositionLatLng();
MarkerOptions phoneMarker = new MarkerOptions().position(latLng).title("Marker");
mMap.addMarker(phoneMarker);
phoneMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(20).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addDevicesMarkers(connectedDevices);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
private void receiveExtraData(Bundle b){
connectedDevices = b.getParcelableArrayList(BundlesKeys.BLUETOOTH_DEVICES_ARRAY);
}
private void getDevicePosition(BluetoothDevice bDevice){
listener.getDeviceLocation(bDevice);
}
private void addDevicesMarkers(ArrayList<BluetoothDevice> list){
if (!list.isEmpty()){
BluetoothDevice device = list.get(0);
getDevicePosition(device);
}
}
public void addMarker(LatLng pos){
MarkerOptions deviceMarker = new MarkerOptions().position(pos).title("Device");
mMap.addMarker(deviceMarker);
}
Somebody knows the fix?? Somebody knows how to program a listener for devices location events?
You just have to use mMap.addMarker() as many times as the number of markers that you want to show. If you are using it only one time, like you are doing inside setUpMap(), you will only see one marker.
Don't forget to change your MarkerOptions attributes for each marker.

Categories

Resources