marker is showing wrong location on google map - android

i have created navigation drawer activity to show my map using map fragment.
my map is visible but it points wrong location.i want to show my current location. i have checked permissions in manifest. I don't know where exactly i have done wrong.
here is mapFragment.java file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryName();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng).title(result));
map.setMaxZoomPreference(20);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

Use this code :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_map, container, false);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
// changes here
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
}
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
//get the location name from latitude and longitude
Geocoder geocoder = new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addresses =
geocoder.getFromLocation(latitude, longitude, 1);
String result = addresses.get(0).getLocality() + ":";
result += addresses.get(0).getCountryName();
LatLng latLng = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions().position(latLng).title(result));
map.setMaxZoomPreference(20);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
}

Related

how i can access current user location in fragments using API28?

i want to access current location in fragments , but i am using API 28 and android version 3.2.1. i try everything from internet follow tutorials but i cant access my current location , there is no error in my code but i don't know why i cant access it. when i run my program i just see google default map, no marker etc.
i want to access my location through network provider as well as gps provider if network provider is not available.
i also add permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
for a permission access i am using library from github and for lacation and map
implementation 'pub.devrel:easypermissions:2.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
please check my code and guide me how i can access current location my code is in below in my code there is also step counter code but ignore that one.
here is my code
public class HomeActivity extends Fragment implements SensorEventListener, OnMapReadyCallback {
SensorManager sensorManager;
TextView set_steps;
TextView set_calories;
TextView set_distance;
boolean running = false;
private static int steps;
private static int calories;
private static double distance;
private GoogleMap mMap;
LocationManager locationManager;
public static final int Request_User_Location_Code = 99;
GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private final int REQUEST_LOCATION_PERMISSION = 1;
Provider provider;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_home, container, false);
requestLocationPermission();
stepsCounter();
locationTracker();
return view;
}
void stepsCounter() {
set_steps = (TextView) view.findViewById(R.id.set_steps);
set_calories = (TextView) view.findViewById(R.id.set_calories);
set_distance = (TextView) view.findViewById(R.id.set_distance);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener((SensorEventListener) getActivity(), countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(getActivity(), "Sensor not Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause() {
super.onPause();
running = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (running) {
steps = (int) event.values[0];
set_steps.setText(steps + "");
caloriesCounter();
distanceCover();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
void caloriesCounter() {
calories = steps / 20;
set_calories.setText(calories + "");
}
void distanceCover() {
distance = (double) steps * 0.76;
String distanceText = Double.toString(distance);
set_distance.setText(distanceText);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
void locationTracker() {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ((ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(getActivity(), perms)) {
// Toast.makeText(getActivity(), "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
but remember i am using ApI 28

why the google maps camera not in my location?

I have code for google maps in fragment android , i want the camera in my location but the camera is in other location and i dont know why this happen
anyone can help me find out why this situation happen
This is my fragment code :
public class FragmentMap extends Fragment implements LocationListener {
MapView mapView;
GoogleMap map;
double latitude;
double longitude;
public String bestProvider;
public Criteria criteria;
#Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.map_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();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
// Updates the location and zoom of the MapView
map.setMyLocationEnabled(true);
criteria = new Criteria();
bestProvider = String.valueOf(MainActivity.locationManager.getBestProvider(criteria, true)).toString();
Location location = MainActivity.locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
CameraUpdate cameraUpdate =
CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
This is my location declaration :
public static LocationManager locationManager;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
your onlocationchange should be -
#Override
public void onLocationChanged(Location location) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(14)
.build();
if (map != null) {
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
this will move camera to your present location.
let me know if it worked for you.

Marker not visible in Google Map Android v2

Hello I need help adding marker to the google map to show my current location. Even after using the addMarker() method and checking the API key, the marker is still not visible. I am able to get latitude, longitude values but the marker is not visible. I am trying to do it for fragment.
Here is my complete code:
public class WhereAmI extends Fragment {
GoogleMap googleMap;
TextView tv;
Location current;
LocationManager lm;
LocationListener locLis;
public static double lat=0.0000;
public static double longi=0.0000;
public static String addressString="Address Not Available";
LatLng Locateme;
public static String disp;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.whereami, container,false);
tv=(TextView) v.findViewById(R.id.textView1);
lm=(LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locLis=new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
switch (arg1) {
case LocationProvider.AVAILABLE:
Toast.makeText(getActivity(), "AVAILABLE", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.OUT_OF_SERVICE:
Toast.makeText(getActivity(), "OUT_OF_SERVICE", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Toast.makeText(getActivity(), "TEMPORARILY_UNAVAILABLE", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getActivity(), provider+" Enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getActivity(), provider+" Disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location loc) {
addressString="";
lat=loc.getLatitude();
longi=loc.getLongitude();
Geocoder gc=new Geocoder(getActivity());
List<Address> address;
try{
address=gc.getFromLocation(lat, longi, 1);
for(int i=0;i<address.size();i++)
{ Address a=address.get(i);
for(int j=0;j<a.getMaxAddressLineIndex();j++){
addressString+=a.getAddressLine(j)+"\n";
}}
disp="Latitude: "+lat+"\n"+"Longitude: "+longi+"\n"+"Address: "+addressString;
tv.setText(disp);
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(lat,longi)).title("Current Location"));
marker.setIcon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, longi)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}catch(Exception e){
e.printStackTrace();
}
}};
return v;
}
#Override
public void onResume() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5, locLis);
super.onResume();
}
#Override
public void onPause() {
lm.removeUpdates(locLis);
super.onPause();
}
}
because you are sending NULL to the parameters i.e Latitude and Longitude.
Make sure you are getting the coordinates to pointer to point.

Not working plot multiple marker getOverlay().add(classobject) not accept

This is my code i want to plot multiple marker in google map
when i write mapview.getoverlay().add(overlaymarker) it is not working
i am not use MapActivity i use fragment so this is not supported getoverlays() please help me.......
fragmnt1.java
public class one extends Fragment implements LocationListener {
MapView mapView;
GoogleMap googleMap;
private boolean mapsSupported = true;
Location location;
double latitude; // latitude
double longitude;
LatLng latlang;
LocationManager manager;
Overlay_Marker overmarker;
frag provider;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RelativeLayout parent = (RelativeLayout) inflater.inflate(R.layout.one, container, false);
mapView = (MapView) parent.findViewById(R.id.map);
provider=new frag(getActivity());
Log.d("spn", "oncreate view");
return parent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
MapsInitializer.initialize(getActivity());
} catch (Exception ex) {
mapsSupported = false;
}
if (mapView != null) {
mapView.onCreate(savedInstanceState);
}
initializeMap();
Log.d("spn", "onactivity created");
}
private void initializeMap() {
if (googleMap == null && mapsSupported) {
mapView = (MapView) getActivity().findViewById(R.id.map);
googleMap = mapView.getMap();
Drawable dmarker=getResources().getDrawable(R.drawable.ic_launcher);
dmarker.setBounds(0, 0, dmarker.getIntrinsicWidth(), dmarker.getIntrinsicHeight());
overmarker=new Overlay_Marker(dmarker,getActivity());
Drawable windmill = getResources().getDrawable(R.drawable.ic_launcher);
Drawable bigBen = getResources().getDrawable(R.drawable.ic_launcher);
Drawable eiffelTower = getResources().getDrawable(R.drawable.ic_launcher);
overmarker.addOverlayItem(52372991, 4892655, "Amsterdam", windmill);
overmarker.addOverlayItem(51501851, -140623, "London", bigBen);
overmarker.addOverlayItem(48857522, 2294496, "Paris", eiffelTower);
//List<Overlay_Marker> temp = (List<Overlay_Marker>) mapView.getOverlay();
// temp.add(overmarker);
mapView.getOverlay().add(overmarker); /// Not working
GetLongitude_Latitude();
}
}
public void GetLongitude_Latitude()
{
manager=(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
location=provider.getLocation(LocationManager.NETWORK_PROVIDER);
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
String provider = manager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = manager.getLastKnownLocation(provider);
manager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
// Toast.makeText(getActivity(), "Location retrieved"+location.getLatitude()+" and "+location.getLongitude(), Toast.LENGTH_SHORT).show();
//else
// Toast.makeText(getActivity(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
Log.d("spn", "location"+location);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
initializeMap();
}
#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 onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude=location.getLongitude();
latlang=new LatLng(latitude, longitude);
MarkerOptions marker=new MarkerOptions().position(latlang);
googleMap.addMarker(marker);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
CameraPosition cameraPosition = new CameraPosition.Builder().target(
latlang).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}

current latitude & longitude in android fragment class

How can i get Current location.i have tried below code but getting null for location-
public class LocationsMapView extends Fragment implements LocationListener, android.location.LocationListener{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationsMapView.this);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
#Override
public void onLocationChanged(Location loc) {
current=new LatLng(loc.getLatitude(),loc.getLongitude());
lat=loc.getLatitude();longi=loc.getLongitude();
Toast.makeText(getActivity(), "location-"+loc.getLatitude(), Toast.LENGTH_SHORT).show();
System.out.println("location.."+lat+"..."+longi+" current .."+current);
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
System.out.println("Location not available");
}
}
}
I have also given permission in manifest-
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try on this way:
public static class XYZ extends Fragment
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
GoogleMap map;
LatLng latlng;
private LocationRequest lr;
private LocationClient lc;
MapFragment mapFragment;
ImageView iv;
private static View view;
public XYZ() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.XYZ, container,
false);
mapFragment = ((MapFragment) this.getActivity()
.getFragmentManager().findFragmentById(R.id.map));
iv = (ImageView) view.findViewById(R.id.iv);
map = mapFragment.getMap();
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
} catch (InflateException e) {
Toast.makeText(getActivity(), "Problems inflating the view !",
Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Google Play Services missing !",
Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lc = new LocationClient(this.getActivity().getApplicationContext(),
this, this);
lc.connect();
}
#Override
public void onLocationChanged(Location l2) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(l2.getLatitude(), l2.getLongitude()), 15);
map.animateCamera(cameraUpdate);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle connectionHint) {
lc.requestLocationUpdates(lr, this);
}
#Override
public void onDisconnected() {
}
}
This is perfect working in my case.

Categories

Resources