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);
}
Related
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));
}
}
Hi i am new for android and in my app i want to show my current location using GoogleApi client and for this i wrote below code but current location is not showing
Map is shows like my below screen shot
Can some one help me please what is problem?
Activity:-
public class GoogleApiClientClass 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.maps_layout);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap gMap) {
mGoogleMap = gMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
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 onConnected(Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
//mGoogleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
}
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 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(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
//place marker at current position
//mGoogleMap.clear();
if (currLocationMarker != null) {
currLocationMarker.remove();
}
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));
currLocationMarker = mGoogleMap.addMarker(markerOptions);
Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();
//zoom to current position:
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
//If you only need one location, unregister the listener
//LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
manifest:-
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.googlemapsdrawroute"
xmlns:android="http://schemas.android.com/apk/res/android">
<permission
android:name="in.wptrafficanalyzer.locationpolyline.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="in.wptrafficanalyzer.locationpolyline.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".GoogleApiClientClass"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--Testing Key-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="my key" />
</application>
</manifest>
screen:-
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
markers = new Hashtable<String, String>();
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 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 location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
//moveMap();
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", " + longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(false) //Making the marker draggable
.title("Current Location")
.visible(true)); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
//Displaying current coordinates in toast
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
moveMap();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
/* mMap.clear();
//Adding a new marker to the current pressed position
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(false));*/
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
try to replace this in your onLocationChanged.
private void locateMyLocation(Location currentLocation) {
mGoogleMap.addMarker(new MarkerOptions()
.title(mContext.getResources().getString(R.string.map_user_location_title))
.anchor(0.0f, 1.0f)
.position(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())));
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), 15.0f));
}
I developed an application for Android in Eclipse with Google maps. The problem is that the blue dot indicating my current location appears always parallel to the road where I am driving, on roads outside cities. But if you are within the city the point already on top of the road.
I'm using this to get my location on the start of the app:
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
then I add the blue dot to the map:
googleMap.setMyLocationEnabled(true);
and then I start listening for location changes:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, 1, this);
My location change function:
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Lat1 = location.getLatitude();
Long1 = location.getLongitude();
if (Lat1 != Lat || Long1 != Long) {
Lat = location.getLatitude();
Long = location.getLongitude();
if (startNav == true) {
googleMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 17));
b = new LatLng(Lat, Long);
if (a != null) {
String urlTopass = makeURL(b.latitude, b.longitude, a.latitude, a.longitude);
new connectAsyncTask(urlTopass).execute();
}
}
}
}
}
My question is why does the blue dot appear parallel to the street instead of on top of it?
Use the FusedLocationProviderAPI. It 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.
#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));
}
}
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.............................");
}
}
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));
}
});