I have the code set so it loads up the map, however it doesn't automatically go to the user's location until they press the zoom button. I would prefer if it started at the users location or at least loaded it up within a few seconds of the map appearing.
Use this code in onMapready
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
mMap.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
mMap.addMarker(mp);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});}}
xml Code Add map like this:
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
Add java code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
}
Add permissions in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
try this code it helps you
Related
Hello everybody I have a problem with LocationManager
I want to get my place position
This my code:
protected LocationManager locationManager;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 10,
10, this);
}
#Override
public void onLocationChanged(final Location location) {
textView = (TextView) findViewById(R.id.label);
textView.setText("My location = Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
Log.e("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("Latitude","status");
}
Manifest
<uses-sdk
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The problem is when I tested in the emulator and on my phone both devices give different results
What can i do help please
//do focus on the last else block of the code and the OnLocationChanged method(which is inside of the
OnMapReady() method)
this else block(contains the code fo rthe lastknown location method) and the onLocationChanged method
contains the code for the location which is being changed (here by passing from the extended controls
avaialable with the emulator,ie the box opens on clicking the downmost option in the emulator.)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
LocationManager locationManager;
LocationListener locationListener;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mMap.clear();
LatLng place = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(place).title("Marker in Sydney").icon(BitmapDescriptorFactory.defaultMarker(HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
mMap.animateCamera(CameraUpdateFactory.zoomTo(3));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
// Add a marker in Sydney and move the camera
if(Build.VERSION.SDK_INT<23)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}else
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
Location lastknownlocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng position=new LatLng(lastknownlocation.getLatitude(),lastknownlocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("The Location is"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
}
}
Add the yellow icon to your second marker just like you did with the first one, like this:
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastknownlocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng position = new LatLng(lastknownlocation.getLatitude(), lastknownlocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(position).title("The Location is").icon(BitmapDescriptorFactory.defaultMarker(HUE_YELLOW)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
Screenshot:
Hope this helps!
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);
I want to show the current location of user on google map but as of now i am not able to show the location.I have a Fragment in which i am writing the code.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
initGamp(rootView);
// Inflate the layout for this fragment
return rootView;
}
initgmap function
public void initGamp(View root) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// check if map is created successfully or not
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), 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;
}
Log.i("MAP","BEFORE LOCATION");
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
Log.i("MAP", "AFTER LOCATION");
LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Toast.makeText(getActivity().getApplicationContext(),"not null",Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20, 0, this);
Log.i("MAP", "END LOCATION");
}
#Override
public void onLocationChanged(Location location) {
Log.i("MAP","CHANGE LOCATION");
Toast.makeText(getActivity().getApplicationContext(),"chnage",Toast.LENGTH_SHORT).show();
mMap.clear();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.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) {
}
All permissions:
<!-- Required to show current location -->
<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" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Above code i have used for showing location but i does not working.I have also button of current location button on tapping that still i don't get current location.
The key here is to wait until the onMapReady() callback has occured before you request location updates. Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap.
Here is the full Activity code that does what you need. Register a location listener when the activity loads then when each location changed event occurs.
Here is the sample activity code:
public class MainActivity extends AppCompatActivity implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap gMap) {
mGoogleMap = gMap;
mGoogleMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnect
I have been debugging this code for long, but could not make it. I am getting correct Longitude & Latitude in listener, but could not update the Map accordingly, Can any one help me on this.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
protected GoogleMap mMap;
protected LocationManager locationManager;
protected LocationListener locationListener;
private double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocation();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Toast.makeText(getApplicationContext(),"Latitude:" + latitude + ", Longitude:" + longitude,Toast.LENGTH_SHORT).show();
LatLng delhiIndia = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(delhiIndia).title("Delhi--India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(delhiIndia));
}
public void getLocation(){
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude =location.getLongitude();
Toast.makeText(getApplicationContext(),"Latitude:" + latitude + ", Longitude:" + longitude,Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
}
}
Can any one help me track the issue, please.
for Add new marker
mMap.clear();
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("My Position")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(marker);
#Override
public void onLocationChanged(Location location) {
latitude=location.getLatitude();
longitude =location.getLongitude();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(3.3f).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
Toast.makeText(getApplicationContext(),"Latitude:" + latitude + ", Longitude:" + longitude,Toast.LENGTH_SHORT).show();
}