How to get current location of device on google maps api v2? - android

I´ve found some methods to do that but are deprecated or doesn´t work. I would like to get current latitude and longitude from device.
Here is how I'm getting the current location, but the GoogleMap getMyLocation() method is deprecated:
void getCurrentLocation()
{
Location myLocation = map.getMyLocation();
if(myLocation!=null)
{
double dLatitude = myLocation.getLatitude();
double dLongitude = myLocation.getLongitude();
map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
else
{
Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
}
}

For targeting api-23 and higher:
See the answer here.
For targeting api-22 and lower:
It's actually quite simple, using the FusedLocationProviderAPI is recommended over using the older open source Location APIs, especially since you're already using a Google Map so you are already using Google Play Services.
Simply set up a Location Listener, and update your current location Marker in each onLocationChanged() callback. If you only want one location update, just un-register for callbacks after the first callback returns.
public class MainActivity extends FragmentActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
buildGoogleApiClient();
mGoogleApiClient.connect();
}
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap retMap) {
map = retMap;
setUpMap();
}
public void setUpMap(){
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
#Override
protected void onPause(){
super.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
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 onConnected(Bundle bundle) {
Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//remove previous current location Marker
if (marker != null){
marker.remove();
}
double dLatitude = mLastLocation.getLatitude();
double dLongitude = mLastLocation.getLongitude();
marker = map.addMarker(new MarkerOptions().position(new LatLng(dLatitude, dLongitude))
.title("My Location").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
}
}

This is working correctly remaining all are deprecated
private FusedLocationProviderClient fusedLocationClient;
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
mylatitude = location.getLatitude();
mylongitude = location.getLongitude();
Log.d("chk", "onSuccess: "+mylongitude);
// Logic to handle location object
}
}
});
This link will be helpful

public class MainActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
GoogleMap.OnMarkerClickListener, LocationListener,
View.OnClickListener {
private static final String TAG = "MapsActivity";
Location mCurrentLocation;
String mLastUpdateTime;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Marker mCurrLocationMarker;
private LocationRequest mLocationRequest;
private ArrayList<LatLng> routePoints;
private Polyline line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
//Initializing googleApiClient
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
routePoints = new ArrayList<LatLng>();
}
#Override
public void onClick(View v) {
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setSmallestDisplacement(0.1F); //added
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //changed
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
// mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
}
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(MainActivity.this, "onMarkerClick", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public void onMarkerDragStart(Marker marker) {
Toast.makeText(MainActivity.this, "onMarkerDragStart", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDrag(Marker marker) {
Toast.makeText(MainActivity.this, "onMarkerDrag", Toast.LENGTH_SHORT).show();
}
#Override
public void onMarkerDragEnd(Marker marker) {
// getting the Co-ordinates
/* latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;*/
//move to current position
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMapOptions.mapType(googleMap.MAP_TYPE_HYBRID)
// .compassEnabled(true);
/* LatLng india = new LatLng(20.5937, 78.9629);
mMap.addMarker(new MarkerOptions().position(india).title("Marker in India"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(india));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);*/
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;
}
mMap.setMyLocationEnabled(true);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
addMarker();
/* //Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
PolylineOptions pOptions = new PolylineOptions()
.width(5)
.color(Color.GREEN)
.geodesic(true);
for (int z = 0; z < routePoints.size(); z++) {
LatLng point = routePoints.get(z);
pOptions.add(point);
}
line = mMap.addPolyline(pOptions);
routePoints.add(latLng);*/
}
private void addMarker() {
MarkerOptions options = new MarkerOptions();
IconGenerator iconFactory = new IconGenerator(this);
iconFactory.setStyle(IconGenerator.STYLE_GREEN);
options.icon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon(mLastUpdateTime)));
options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());
LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
options.position(currentLatLng);
mCurrLocationMarker = mMap.addMarker(options);
long atTime = mCurrentLocation.getTime();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
mCurrLocationMarker.setTitle(mLastUpdateTime);
Log.d(TAG, "Marker added.............................");
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng,
18));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
PolylineOptions pOptions = new PolylineOptions()
.width(5)
.color(Color.BLACK)
.geodesic(true);
for (int z = 0; z < routePoints.size(); z++) {
LatLng point = routePoints.get(z);
pOptions.add(point);
}
line = mMap.addPolyline(pOptions);
routePoints.add(currentLatLng);
Log.d(TAG, "Zoom done.............................");
}
}

Related

Bearing and location

Got some strange thing here while doing task of map rotation around user current location marker. So what i am trying to do is like google maps application on second "Current location" tap. Marker must keep its position at map center while map is moving.
As i understood need to use bearing value to update camera position object on GoogleMap v2.
CameraUpdate cameraUpdatePos;
CameraPosition.Builder currentPlaceBuilder = new CameraPosition.Builder().target(loc);
if (location.hasBearing())
currentPlaceBuilder.bearing(location.getBearing());
cameraUpdatePos = CameraUpdateFactory.newCameraPosition(currentPlaceBuilder.build());
map.animateCamera(cameraUpdatePos);
The bug is about every location returns every time false hasBearing() call result and bearing 0.0 with my app. But google maps app shows me my direction at this time properly.
I am using service
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
googleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(gmsCallbacks)
.addOnConnectionFailedListener(gmsCallbacks)
.addApi(LocationServices.API)
.build();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(25 * 1000)
.setFastestInterval(5 * 1000)
.setSmallestDisplacement(1);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
.setAlwaysShow(true);`
and method onconnected
`#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
return;
Log.i(TAG, "Connected");
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, gmsCallbacks);
if (locationChangeCallback != null)
locationChangeCallback.onLocationChanged(location);
}`
Does anybody knows how google map made their bearing calculation for auto orientation map mode ?
Maybe someone has such situation and could help me with advice. Thanks.
May this helps you
public class GoogleApiActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener , {
SupportMapFragment fragment;
GoogleMap googleMap;
GoogleApiClient googleApiClient;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_api);
mapLoading();
googleClientApi();
}
private void mapLoading(){
FragmentManager manager = getSupportFragmentManager();
fragment = (SupportMapFragment) manager.findFragmentById(R.id.map_space);
if (fragment == null)
{
fragment = SupportMapFragment.newInstance();
manager.beginTransaction().replace(R.id.map_space, fragment).commit();
}
}
#Override
protected void onResume(){
super.onResume();
if (googleMap == null){
fragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap){
this.googleMap = googleMap;
Toast.makeText(this, "Map Ready CallBack", Toast.LENGTH_SHORT).show();
this.googleMap.setTrafficEnabled(true);
this.googleMap.setIndoorEnabled(true);
this.googleMap.setBuildingsEnabled(true);
this.googleMap.getUiSettings().setZoomControlsEnabled(true);
this.googleMap.setOnCameraChangeListener(this);
}
private void googleClientApi(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(#Nullable Bundle bundle){
LocationRequest locationRequest = createLocationRequest();
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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, createLocationRequest(),GoogleApiActivity.this);
}
#Override
public void onConnectionSuspended(int i){
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult){
}
public LocationRequest createLocationRequest()
{
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(0);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(0);
return locationRequest;
}
#Override
protected void onStart()
{
super.onStart();
if (googleApiClient != null)
{
googleApiClient.connect();
}
}
#Override
protected void onStop()
{
super.onStop();
if (googleApiClient != null)
{
googleApiClient.disconnect();
}
}
#Override
public void onLocationChanged(Location location){
Toast.makeText(this, "Inside onLocationChanged "+location.getAccuracy(), Toast.LENGTH_SHORT).show();
if (location != null)
{
if (marker == null){
marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("My Location"));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 18));
}else{
marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
updateCameraBearing(googleMap, location.getBearing(),location);
}
} }
private void updateCameraBearing(GoogleMap googleMap, float bearing, Location location) {
if ( googleMap == null) return;
CameraPosition camPos = CameraPosition
.builder(
googleMap.getCameraPosition() // current Camera
).target(new LatLng(location.getLatitude(),location.getLongitude()))
.bearing(bearing)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
}
}

Add marker on a map Android

I have an Application in which,I get the user current location and add the marker on a Current location and it's perfectly works but i have some lat and lon and i want to show on map with Marker
Lat,Lon is in workshopList
My code :
public class FindServiceProviders extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
ArrayList<ServiceProviderItem> workshopList;
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_service_providers);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
init();
}
private void init()
{
setToolBar();
workshopList = new ArrayList<ServiceProviderItem>();
mRecyclerView=(RecyclerView)findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager=new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
fetchServiceProviders();
mAdapter=new ServiceProviderAdapter(this,workshopList);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
markerOptions.anchor(.5f,.95f);
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,12f));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
private void fetchServiceProviders()
{
//volley call and populate in list
}
}
you can simply use this method:
#Override
public void onMapReady(GoogleMap map) {
for(ServiceProviderItem item : workshopList){
map.addMarker(new MarkerOptions()
.position(new LatLng(item.lat, item.lng))
.title("Hello world"));
}
}
try this:
private GoogleMap googleMap;
private MarkerOptions options = new MarkerOptions();
private ArrayList<LatLng> latlngs = new ArrayList<>(); //define arraylist of latlng
you can add lat long to the Arraylist using
latlngs.add(new LatLng(21.334343, 92.43434));
Now for showing them on Map use a for loop
for (LatLng point : latlngs) {
options.position(point);
options.title("Marker Title");
options.snippet("Marker Desc");
googleMap.addMarker(options);
}

Nearest location returns null

I have an arraylist of locations marker. I have this method to sort the list. I then assign the first lat and long in the list to a variable so I can get the nearest store.
Collections.sort(marker, new Comparator<Markers>() {
#Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
However, when I use the nearest variable to put a marker on it, no marker was posted on the map. When I checked the value of nearest it does not contain any coordinates. Am I missing on something? Here is my whole MapsActivity.java:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static LatLng nearest;
private static Location currPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
fetchData();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(nearest.latitude,nearest.longitude))
.title("Nearest Store"));
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public void fetchData() {
new AsyncTask() {
private List<Markers> marker;
private JSONArray jsonArray;
#Override
protected void onPreExecute() {
super.onPreExecute();
marker = new ArrayList();
}
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
try {
Intent mapsIntent = getIntent();
String jSonArray = mapsIntent.getStringExtra("jsonArray");
jsonArray = new JSONArray(jSonArray);
for(int i = 0; i < jsonArray.length(); i++) {
Markers branch = new Markers();
branch.latitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
branch.longitude = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
marker.add(branch);
}
Collections.sort(marker, new Comparator<Markers>() {
#Override
public int compare(Markers a, Markers b) {
Location locationA = new Location("point A");
locationA.setLatitude(a.latitude);
locationA.setLongitude(a.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(b.latitude);
locationB.setLongitude(b.longitude);
float distanceOne = currPos.distanceTo(locationA);
float distanceTwo = currPos.distanceTo(locationB);
return Float.compare(distanceOne, distanceTwo);
}
});
nearest = new LatLng(marker.get(0).latitude, marker.get(0).longitude);
} catch (Exception ex) {
Log.d("Error", ex.toString());
}
}
}.execute();
}
private class Markers {
public float latitude;
public float longitude;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
currPos = location;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
There's a race condition between your two threads.
mapFragment.getMapAsync(this); // thread 1
fetchData(); // thread 2
Thread 1 needs Thread 2 to finish and assign nearest to work. Otherwise it is null
You could call mapFragment.getMapAsync(MapsActivity.this); at the end of onPostExecute, but...
Your Asynctask is pointless at the moment because no data is being fetched by a background task.

Google Map (SupportMapFragment) Not Displaying marker in view pager fragments

Hello I have implemented SupportMapFragment for google map and trying to set my location button and marker on google map (SupportMapFragment) but it is not displaying but this code is working in Activity.
Please find the below code for more information.
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private static View view;
private SupportMapFragment mMap;
private static Double latitude, longitude;
GoogleMap gMap;
private static final int PERMISSION_REQUEST_CODE = 1;
public MapsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_map, container, false);
latitude = 26.78;
longitude = 72.56;
FragmentManager fm = getChildFragmentManager();
mMap = (SupportMapFragment) fm.findFragmentById(R.id.map);
if (mMap == null) {
mMap = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMap).commit();
mMap.getMapAsync(this);
}
return view;
}
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(49.39, -124.83), 20));
gMap.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
gMap.getUiSettings().setZoomGesturesEnabled(true);
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
gMap.setMyLocationEnabled(true);
} else {
requestPermission();
}
}
}
Replace your code from this
if **(mMap != null)** {
mMap = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map, mMap).commit();
mMap.getMapAsync(this);
}
import com.google.android.gms.maps.SupportMapFragment;
SupportMapFragment mMapFragment = SupportMapFragment.newInstance();
FragmentManager fm = fragment.getChildFragmentManager();
fm.beginTransaction().add(R.id.map, mMapFragment).commit();
mMapFragment.getMapAsync(this);
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.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;
}
mGoogleMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.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;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
mGoogleMap.clear();
//setLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(50000); //50 seconds
mLocationRequest.setFastestInterval(30000); //30 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(customAdapter.getContext(), "onConnectionSuspended", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(customAdapter.getContext(), "onConnectionFailed", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
sourceLat = location.getLatitude();
sourceLng = location.getLongitude();
getRestaurantDetails();
latLng = new LatLng(location.getLatitude(), location.getLongitude());
//latLng = new LatLng(lat, lng);
//Log.wtf("Lat lng", lat + " " + lng);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
where fragment is instance of your viewPagerFragment
in xml
<LinearLayout
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="250dp" />
try this
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);
}
}
Refer here for detail:- http://coderzpassion.com/android-google-maps-v2-tutorial-with-markers/
Maybe you don't yet have the permission when you're using setMyLocation();. Try this -
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_DENIED){
FragmentCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST);
}
The handle the result -
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST && grantResults.length > 0) {
if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Calling the function here
gMap.setMyLocationEnabled(true);
}
else
Toast.makeText(context, "You need to provide " +
"permission to find the location", Toast.LENGTH_LONG).show();
}
}
}
I had the same problem with viewpager and I solved it using OnMapLoaded callback. Try doing this
public class MapsFragment extends Fragment implements OnMapReadyCallback,
GoogleMap.OnMapLoadedCallback {
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setOnMapLoadedCallback(this);
}
//map loaded callback
#Override
public void onMapLoaded() {
// add your marker now
gMap.addMarker(new MarkerOptions()
.position(new LatLng(37.7750, 122.4183))
.title("San Francisco")
.snippet("Population: 776733"));
}
}

How to show current position marker on Map in android?

I am developing an application in which I want to display current location using marker in my map. I am using Google Map v2. Here I can display Map and marker when GPS is off ,but not visible any marker on map when GPS on. My requirement is display marker on map with current position
I tried like this,
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
this);
ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>)
getIntent().getSerializableExtra("arrayList");
if(location!=null){
double latitude = location.getLatitude();
double langitude = location.getLongitude();
myPosition = new LatLng(latitude, langitude);
CameraPosition position= new CameraPosition.Builder().
target(myPosition).zoom(17).bearing(19).tilt(30).build();
//_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
_googleMap.addMarker(new
MarkerOptions().position(myPosition).title("start"));
}
Use below code it worked for me:
#Override
public void onLocationChanged(Location location) {
map.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
map.addMarker(mp);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
Try this,it is showing current location:
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Try this:-
private void initMap() {
if (googleMap != null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// to set current location
googleMap.setMyLocationEnabled(true);
Marker pos_Marker = googleMap.addMarker(new MarkerOptions().position(starting).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_laumcher)).title("Starting Location").draggable(false));
pos_Marker.showInfoWindow();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(START_locationpoint, 10));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15),2000, null);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Use this. It works for me.
#Override
public void onLocationChanged(Location location) {
map.clear();
mp1 = new MarkerOptions();
mp1.position(new LatLng(location.getLatitude(),
location.getLongitude()));
mp1.draggable(true);
mp1.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
map.addMarker(mp1);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 20));
}
You may try this:
public class MapsActivity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private Circle mCircle;
double radiusInMeters = 100.0;
int strokeColor = 0xffff0000; //Color Code you want
int shadeColor = 0x44ff0000; //opaque red fill
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getSupportActionBar().setTitle("Map Location Activity");
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
//mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
#Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
CircleOptions addCircle = new CircleOptions().center(latLng).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = mGoogleMap.addCircle(addCircle);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Location mlocation;
#Override
public void onLocationChanged(Location location) {
// Add a marker in Sydney and move the camera
mLocation = location;
LatLng myLocation = new LatLng(mLocation.getLatitude(), mLocation.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(myLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.title("My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
Log.d("location", "Latitude:" + mLocation.getLatitude() + "\n" + "Longitude:" + mLocation.getLongitude());
}
for getting current position you can use getLastKnownLocation() method on LocationManager:
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Location currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng current = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(current).title("Marker Label").snippet("Marker Description"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(current).zoom(14).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
float lat = (float) latLng.latitude;
float lon = (float) latLng.longitude;
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in " + lat +" "+ lon));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
});

Categories

Resources