I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:
LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());
Then I recalled the addMarker method:
mMap.addMarker(new MarkerOptions()
.title(getString(R.string.default_info_title))
.position(mCurrentPlace)
.snippet(getString(R.string.default_info_snippet)))
But Launching the application by "Run", it arrested.
Where am I goning wrong?
Thanks.
public void moveMap(GoogleMap gMap, double latitude, double longitude) {
Log.v(TAG, "mapMoved: " + gMap);
LatLng latlng = new LatLng(latitude, longitude);
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
gMap.addMarker(new MarkerOptions().position(latlng));
gMap.moveCamera(cu);
}
Call this method where you want location and marker and in on mapasync callback method.
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(context);
gMap = googleMap;
gMap.getUiSettings().setMapToolbarEnabled(false);
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if(items.get(getLayoutPosition())!=null )
moveMap(gMap,latitude, longitude);
}
public void initializeMapView() {
if (mapView != null) {
// Initialise the MapView
mapView.onCreate(null);
// Set the map ready callback to receive the GoogleMap object
mapView.getMapAsync(this);
}
}
Override onMapReadyCallback method and do this.
Call initializeMapView method in onCreate() or In adapter onBindViewHolder
Try using the LatLng.Builder
LatLng.Builder builder = LatLng.newBuilder();
builder.setLatitude(location.getLatitude());
builder.setLongitude(location.getLongitude());
latLng = builder.build();
MAP Activity
public class MapsActivity2 extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
LatLng loc;
Location location;
private double currentLatitude = 0;
private double currentLongitude = 0;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
/**
* 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 atLnmove 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.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker
in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLg(sydney));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(MapsActivity2.this);
}
public double getLatitude(){
if(location != null){
currentLatitude = location.getLatitude();
}
// return latitude
return currentLatitude;
}
public double getLongitude(){
if(location != null){
currentLongitude = location.getLongitude();
}
// return longitude
return currentLongitude;
}
#Override
public boolean onMyLocationButtonClick() {
location=mMap.getMyLocation();
currentLatitude=getLatitude();
currentLongitude=getLongitude();
LatLng currentLocation = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));
return false;
}
}
Resource XML
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.atziant.parashar.gmapsapi.MapsActivity2" />
Related
I don't know how to follow the user's location using a service with GPS.
1. You have to create the project using Google Maps Activity:
2. You have to create the Google API key following the link in the comment and insert it here:
3. Make sure to add these permissions in your Manifest.xml :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
4. This is an example of the Maps Activity code to get the user's current position:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
private static final int REQUEST_LOCATION_PERMISSION = 1;
Marker marker;
LocationListener locationListener;
#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);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, 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(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);
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
marker = mMap.addMarker(new MarkerOptions().position(latLng).title(result));
mMap.setMaxZoomPreference(20);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 21.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);
}
/**
* 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.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
protected void onStop() {
super.onStop();
locationManager.removeUpdates(locationListener);
}}
to start with, I am completely confused with various api's available for location and map. So, I even dont know if the code is optimal for sdk 27.(I have minimum sdk 24 set.)
The problem is this piece of code shows the current location well and fine, butand the map gets updated when the location is changed. But, that is not reflected in location. See, the polyline drawn from LatLong does not follow the current location.
Also, I am trying to implement FusedLocationProviderClient but thats probably not the case here.
Any help will be very welcome.
public class SecondFragment extends Fragment implements OnMapReadyCallback {
//Color stroke = new Color(222.0,135.0, 135.0,174.0);
private GoogleMap mMap;
public static SecondFragment newInstance() {
SecondFragment fragment = new SecondFragment();
return fragment;
}
public GoogleMap getMap() {
return mMap;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double latitude;
double longitude;
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
latitude = 0.0;
longitude = 0.0;
} else {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
latlang.Lat = latitude;
latlang.Lang = longitude;
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(18).build();
double angle = Math.toRadians(93.833);
Point cPoint = mMap.getProjection().toScreenLocation(new LatLng(latitude,longitude));
System.out.println("mPoint X"+ cPoint.x);
System.out.println("mPoint Y"+ cPoint.y);
Point mPoint = new Point();
//Azimuth Pos only
double lat_azi = 2*Math.sin(angle)+cPoint.y;
double long_azi = 2*Math.cos(angle)+cPoint.x;
LatLng nat_azi =mMap.getProjection().fromScreenLocation(mPoint);
//private List<Point> mPoint = new ArrayList<Point>();
Marker marker = mMap.addMarker(new MarkerOptions()
.position(nat_azi)
.anchor(0.5f,0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.sun_pos_icon))
);
Marker marker_loc = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon))
);
mMap.addPolyline(new PolylineOptions()
.add(new LatLng(lat_azi, long_azi), new LatLng(latitude, longitude), new LatLng(0,0))
.width(15)
.color(Color.MAGENTA));
PathOfSun.getTime();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true); // true to enable
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
}
}
}
You can follow below link for Updating Marker position on the Map.
Move marker with gps in google map android
I'm trying to display the current location of the user on the google map inside my app but I don't want to keep updating the location as the user moves. His initial location should be recorded and showed until he closes the app. I have written the following code for this:
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
Location mLastLocation;
double lat =0, lng=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
buildGoogleApiClient();
// 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);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* 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.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
mMap.setMyLocationEnabled(true);
LatLng loc = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
The problem with this code is that I'm getting the lat, lng after the onMapReady function has already finished executing. I thought that one of the ways to correct this would be create an AsyncTask to ensure that the location data is retrieved before the map. However, I'm trying to implement this in a way that won't use AsyncTask.
Just move the code that creates the Markers from onMapReady() to onConnected(), and move the call buildGoogleApiClient() call from onCreate() to onMapReady():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//buildGoogleApiClient();
// 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(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
mMap.setMyLocationEnabled(true);
//add this here:
buildGoogleApiClient();
//LatLng loc = new LatLng(lat, lng);
//mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
lat = mLastLocation.getLatitude();
lng = mLastLocation.getLongitude();
LatLng loc = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(loc).title("New Marker"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
}
}
Although, note that you will frequently get null from the call to getLastLocation(). You can use requestLocationUpdates(), and call removeLocationUpdates() when the first location comes in.
Take a look at this answer, it has a complete example of exactly what you're trying to do.
My code is totally fine, i want to get user location on the map as soon as the app is opened. But the app just crashes. Also the program is set to update location and add a marker as soon as its changed, nut that's also is not working. Here's the code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
#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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location= locationManager.getLastKnownLocation(provider);
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
// Add a marker and move the camera
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
Log.i("Latitude", lat.toString());
}
try This.
getLastKnownLocation returns if location is there in cache otherwise it returns null
add a check there
if(location!=null)
{
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Marker"));
}
2 solution use google play services fusedlocation api for better management with location refer here http://coderzpassion.com/android-location-using-google-play-services/
3 try this to addMarker
public void drawMarker(double lat,double lon)
{
if (mMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Moving Camera to a Location with animation
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.addMarker(marker);
}
}
for more details refer here http://coderzpassion.com/android-google-maps-v2-tutorial-with-markers/
I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.
I want to simulate that button press in my code. I am familiar with the LocationManager and LocationListener classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.
If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager/LocationListener classes, right?
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
After you instansiated the map object (from the fragment) add this -
private void centerMapOnMyLocation() {
map.setMyLocationEnabled(true);
location = map.getMyLocation();
if (location != null) {
myLocation = new LatLng(location.getLatitude(),
location.getLongitude());
}
map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
Constants.MAP_ZOOM));
}
if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
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.moveCamera(center);
mMap.animateCamera(zoom);
}
});
try this code :
private GoogleMap mMap;
LocationManager locationManager;
private static final String TAG = "";
#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(map);
mapFragment.getMapAsync(this);
arrayPoints = new ArrayList<LatLng>();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
LatLng myPosition;
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) {
// 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;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
mMap.animateCamera(yourLocation);
}
}
}
Dont forget to add permissions on AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
private void setUpMapIfNeeded(){
if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file
if (mMap != null) {
mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.
LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
String provider=lm.getBestProvider(new Criteria(), true);
if(provider==null){
onProviderDisabled(provider);
}
Location loc=lm.getLastKnownLocation(provider);
if (loc!=null){
onLocationChanged(loc);
}
}
}
}
// Initialize map options. For example:
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
#Override
public void onLocationChanged(Location location) {
LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}
// TODO Auto-generated method stub
check this out:
fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
val request = LocationRequest()
// request.interval = 10000
// request.fastestInterval = 5000
request.numUpdates = 1
request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
val client = LocationServices.getFusedLocationProviderClient(context)
val permission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION )
if (permission == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(request, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
if (location != null)
callback.invoke(location)
}
}, null)
}
}
and
fun zoomOnMe() {
requestMyGpsLocation(this) { location ->
mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude,location.longitude ), 13F ))
}
}
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
In kotlin, you will get the current location then move the camera like this
map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
}
}
Also you can animate the move by using this function instead
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.latitude, location.longitude), 14f))