I am working on maps in my application. In which i used InfoWindowAdapter. I am having image view in that. But on opening the info window image is not display.
The xml of infoWindow is as follow:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageView_infoWindow"
android:layout_width="80dp"
android:layout_height="80dp"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
And the Activity code is as follow:
public class LocationActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationChangeListener, GoogleMap.OnMyLocationButtonClickListener {
private GoogleMap mMap;
public LatLng MOUNTAIN_VIEW;
int METERS = 20000;
final private int PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION = 123;
List<MarkerOptions> markerOptionsList;
ArrayList<ModelLocation> modelLocation;
protected LocationManager locationManager;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
ImageLoader mImageLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setElevation(2);
actionBar.setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
actionBar.setTitle("Location");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setIndoorLevelPickerEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
if (checkPermission()) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
} else {
requestPermission();
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(MOUNTAIN_VIEW)
.zoom(17)
.bearing(360)
.tilt(45)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
final LatLng latLng = cameraPosition.target;
final Location location = new Location("Camera_Location");
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
final ProgressDialog progressDialog = new ProgressDialog(LocationActivity.this, R.style.ProgressBarTansparent);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.setContentView(R.layout.custom_progressbar_layout);
String url = "My URL To Get Data";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Key","Value");
} catch (JSONException e) {
e.printStackTrace();
}
final JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayUserList = response.getJSONArray("ABC");
modelLocation = new ArrayList<>();
int size = jsonArrayUserList.length();
if (size > 0) {
for (int count = 0; count < size; count++) {
JSONObject jsonObject = jsonArrayUserList.getJSONObject(count);
int userID = jsonObject.getInt("userID");
String Name = jsonObject.getString("address");
String address = jsonObject.getString("ADD");
float latitude = Float.parseFloat(jsonObject.getString("latitude"));
float longitude = Float.parseFloat(jsonObject.getString("longitude"));
String image = jsonObject.getString("image");
ModelLocation modelLocation1 = new ModelLocation(userID, Name, address, latitude, longitude, image);
modelLocation.add(modelLocation1);
}
Location target = new Location("target");
for (ModelLocation modelLocation1 : modelLocation) {
target.setLatitude(modelLocation1.latitude);
target.setLongitude(modelLocation1.longitude);
LatLng point = new LatLng(modelLocation1.latitude, modelLocation1.longitude);
MarkerOptions markerOptions = new MarkerOptions().title(modelLocation1.Name).snippet(modelLocation1.address).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).anchor(0.0f, 1.0f).position(point);
if (location.distanceTo(target) < METERS) {
if (isMarkerOnArray(markerOptionsList, markerOptions)) {
} else {
markerOptionsList.add(markerOptions);
Marker marker = mMap.addMarker(markerOptions);
dropic_pinEffect(marker);
}
}
}
}
progressDialog.dismiss();
} catch (Exception e) {
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}
};
Volley.newRequestQueue(LocationActivity.this).add(postRequest);
}
});
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.info_window_layout, null);
LatLng latLng = marker.getPosition();
for (int count = 0; count < modelLocation.size(); count++) {
double currentLat = modelLocation.get(count).getLatitude();
double currentLng = modelLocation.get(count).getLongitude();
if ((currentLat == latLng.latitude) && (currentLng == latLng.longitude)) {
TextView textViewTitle = (TextView) view.findViewById(R.id.textView_title);
TextView textViewAddress = (TextView) view.findViewById(R.id.textView_address);
TextView textViewLocation = (TextView) view.findViewById(R.id.textView_location);
final NetworkImageView imageViewUserImage = (NetworkImageView) view.findViewById(R.id.imageView_infoWindow);
textViewTitle.setText("" + modelLocation.get(count).getName());
textViewAddress.setText("" + modelLocation.get(count).getAddress());
textViewLocation.setText(currentLat + ", " + currentLng);
mImageLoader = VolleySingletonClass.getInstance(LocationActivity.this).getImageLoader();
String url = "My URL Of Image";
imageViewUserImage.setImageUrl(url, mImageLoader);
imageViewUserImage.setDefaultImageResId(R.drawable.ic_user_default);
imageViewUserImage.setErrorImageResId(R.drawable.ic_user_default);
}
}
return view;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(LocationActivity.this, Activity2.class);
startActivity(intent);
finish();
}
});
}
static boolean isMarkerOnArray(List<MarkerOptions> listMarkerOptions, MarkerOptions markerOptions) {
for (int count = 0; count < listMarkerOptions.size(); count++) {
MarkerOptions current = listMarkerOptions.get(count);
if ((current.getPosition().latitude == markerOptions.getPosition().latitude) && (current.getPosition().longitude == markerOptions.getPosition().longitude))
return true;
}
return false;
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(LocationActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
}
#SuppressLint("NewApi")
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
mMap.setOnMyLocationButtonClickListener(this);
} else {
Toast.makeText(LocationActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(LocationActivity.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, PERMISSION_REQUEST_CODE_FOR_ACCESS_LOCATION);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void dropic_pinEffect(final Marker marker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 1000;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0);
marker.setAnchor(0.5f, 1.0f + 7 * t);
if (t > 0.0) {
handler.postDelayed(this, 15);
} else {
}
}
});
}
#Override
public void onMyLocationChange(Location location) {}
#Override
public boolean onMyLocationButtonClick() {
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onResume() {
super.onResume();
getLocation();
if (canGetLocation()) {
double lat = getLatitude();
double lng = getLongitude();
MOUNTAIN_VIEW = new LatLng(lat, lng);
markerOptionsList = new ArrayList<MarkerOptions>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
showSettingsAlert();
}
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public Location getLocation() {
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public double getLatitude() {
double lati = 0;
if (location != null) {
lati = location.getLatitude();
}
return lati;
}
public double getLongitude() {
double longi = 0;
if (location != null) {
longi = location.getLongitude();
}
return longi;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
Intent intent = new Intent(LocationActivity.this, Activity1.class);
startActivity(intent);
finish();
}
});
alertDialog.show();
}
}
I searched on Google that why image is not display, So i got to know that i need to refresh info window adapter may be. Or is it Volley implementation issue?
Please suggest me That my implementation is right or not and what step should i perform to Display Image in image view on window open
Related
I'm making an app to display the five nearest Subway stations. I'm able to get the names of the stations back and populate a list view with the data.
I'm getting lng&lat from the API and would like to add pins to the map using these coordinates. I've got the map working, I'm able to display a single pin, but not multiple pins. A point in the correct direction would be much appreciated - Please see code below.
public class nearMe extends AppCompatActivity implements OnMapReadyCallback {
private MapView mapView;
public GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
// Location Co-ordinates
private String lat = "";
private String lng = "";
LocationManager locationManager;
LocationListener locationListener;
private List<Station> stationList = new ArrayList<>();
private RecyclerView recyclerView;
private stationAdapter mAdapter;
/* LOCATION STUFF */
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
}
public void updateLocationInfo(Location location) {
lat = "" + location.getLatitude();
lng = "" + location.getLongitude();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
getNearestStations();
Toast.makeText(this, "Location Updated!", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_me);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new stationAdapter(stationList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
// onClick
recyclerView.addOnItemTouchListener(new TouchListener(getApplicationContext(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// Toast.makeText(getApplicationContext(), stationList.get(position).getStation() + "", Toast.LENGTH_SHORT).show();
String findStation = stationList.get(position).getStation();
// Toast.makeText(nearMe.this, bob, Toast.LENGTH_SHORT).show();
Uri gmmIntentUri = Uri.parse("google.navigation:q="+findStation+"underground station+London&mode=w");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(mapIntent.FLAG_ACTIVITY_CLEAR_TOP);
if (mapIntent.resolveActivity(getPackageManager()) != null) {
startActivity(mapIntent);
}
}
}));
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocationInfo(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
startListening();
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
updateLocationInfo(location);
}
}
}
// insert Stations in to recycler
getNearestStations();
//map
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY);
}
mapView = (MapView) findViewById(R.id.map_view);
mapView.onCreate(mapViewBundle);
mapView.getMapAsync(this);
}
// clear adapter before adding
public void clear() {
int size = this.stationList.size();
this.stationList.clear();
mAdapter.notifyItemRangeRemoved(0, size);
}
public void getNearestStations(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=157c4895&app_key=091697cea8bae89519dd02ebb318fc51&lat=" + lat + "&lon=" + lng + "&rpp=5";
final StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("stations");
// Call 'Clear' method to clear mAdapter before adding new data
clear();
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
String station = jObject.getString("name");
Station newStation = new Station(station);
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
double longitude = Double.parseDouble(lng);
double latitude = Double.parseDouble(lat);
gmap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(station));
}
}else{
Station newStation = new Station("No stations near");
stationList.add(newStation);
mAdapter.notifyDataSetChanged();
// Show a diaog
AlertDialog alertDialog = new AlertDialog.Builder(nearMe.this).create();
alertDialog.setTitle("No Stations Found");
alertDialog.setMessage("You are either not in London or you have no network connectivity.");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}); alertDialog.show();
}
} catch (JSONException e) { }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
// maps
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
mapView.onSaveInstanceState(mapViewBundle);
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onPause() {
mapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
Let's say your API returns data in the markers array.
for(int i = 0 ; i < markers.size() ; i++ ) {
createMarker(markers.get(i).getLatitude(), markers.get(i).getLongitude(), markers.get(i).getTitle(), markers.get(i).getSnippet(), markers.get(i).getIconResID());
}
...
protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {
return googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet);
.icon(BitmapDescriptorFactory.fromResource(iconResID)));
}
I've a very strange problem with using google map in my application , I've build an application , it shows the map in my phone and it has not problem but it doesn't show in another phone , it has a white screen like this :
and then it shows this:
on the same phone, in another app it shows map with no problem .
could you help me ?
this is my code :
public class Maps extends AppCompatActivity {
FetchCordinates fetchCordinates;
Intent locatorService = null;
MapView mMapView;
private GoogleMap googleMap;
Double lat = 0.0, lon = 0.0;
Typeface typeface;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
typeface = Func.getTypeFace(this);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mapBuilder();
try {
Bundle bl = getIntent().getExtras();
if (bl != null) {
lat =(bl.getDouble("lat"));
lon = (bl.getDouble("lon"));
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
} catch (Exception e) {
}
}
private void mapBuilder() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& checkSelfPermission(
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Maps.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
doGPS();
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
e.printStackTrace();
}
Button mapbutton=(Button)findViewById(R.id.mapbutton);
mapbutton.setTypeface(typeface);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences("settings", MODE_PRIVATE);
SharedPreferences.Editor pref= settings.edit();
pref.putString("lat", lat+"");
pref.putString("lon", lon+"");
pref.commit();
onBackPressed();
}
});
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mapBuilder();
} else {
MyToast.makeText(Maps.this, "دسترسی به جی پی اس غیرفعال است");
}
return;
}
}
}
public boolean stopService() {
if (this.locatorService != null) {
this.locatorService = null;
}
return true;
}
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
public AlertDialog CreateAlert(String title, String message) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle(title);
alert.setMessage(message);
return alert;
}
public class FetchCordinates extends AsyncTask<String, Integer, String> {
AlertDialog.Builder a;
AlertDialog dialog;
public double lati = 0.0;
public double longi = 0.0;
public LocationManager mLocationManager;
public VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
try {
if(dialog!=null)
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
lat = lati;
lon = longi;
MyToast.makeText(Maps.this, "موقعیت شما با موفقیت ثبت شد");
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
mMapView.setVisibility(View.VISIBLE);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(sydney).title(""));
googleMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 22));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0) {
}
return null;
}
public class VeggsterLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) location.getLatitude(); // * 1E6);
int log = (int) location.getLongitude(); // * 1E6);
int acc = (int) (location.getAccuracy());
String info = location.getProvider();
try {
// LocatorService.myLatitude=location.getLatitude();
// LocatorService.myLongitude=location.getLongitude();
lati = location.getLatitude();
longi = location.getLongitude();
} catch (Exception e) {
// progDailog.dismiss();
// Toast.makeText(getApplicationContext(),"Unable to get Location"
// , Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i("OnProviderDisabled", "OnProviderDisabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "onProviderEnabled");
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
Log.i("onStatusChanged", "onStatusChanged");
}
}
}
private void doGPS() {
try {
LocationManager mlocManager = null;
LocationListener mlocListener;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startService();
} else {
android.support.v7.app.AlertDialog.Builder a = new android.support.v7.app.AlertDialog.Builder(Maps.this);
a.setMessage(("جی پی اس خاموش است. آیا میخواهید روشن کنید؟"));
a.setPositiveButton(("بله"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
});
a.setNegativeButton(("خیر"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
android.support.v7.app.AlertDialog dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
} catch (Exception e) {
MyToast.makeText(Maps.this, e.getMessage());
}
}
#Override
protected void onStart() {
super.onStart();
if (mMapView != null && mMapView.getVisibility() == View.VISIBLE)
mapBuilder();
}
could you help me ?
Google map is not Displaying in the API level 23,24,25 but it is shown kitkat.Why is that Happening?
NearMe
public class NearMe extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
GpsLocation gpsLocation;
double longitude, latitude;
private ProgressDialog pDialog;
ArrayList<MySchool> al_school = new ArrayList<MySchool>();
ArrayList<MyCollege> al_college = new ArrayList<MyCollege>();
ArrayList<MyUniversity> al_university = new ArrayList<MyUniversity>();
private static final String TAG = NearMe.class.getSimpleName();
private static final String urlSchool = "http://www.myeducationhunt.com/api/v1/schools";
private static final String urlCollege = "http://www.myeducationhunt.com/api/v1/colleges";
private static final String urlUniversity = "http://www.myeducationhunt.com/api/v1/universities";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_near_me, container, false);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (isConnected()) {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getContext(), "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
gpsLocation = new GpsLocation(getContext());
if (gpsLocation.canGetLocation()) {
longitude = gpsLocation.getLongitude();
latitude = gpsLocation.getLatitude();
Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
}
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Loading…");
pDialog.show();
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(11).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
drawSchoolMarker();
drawCollegeMarker();
drawUniversityMarker();
}
});
}
else{
showGPSDisabledAlertToUser();
}
} else {
Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
return v;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void drawSchoolMarker() {
JsonArrayRequest schoolRequest = new JsonArrayRequest(urlSchool,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MySchool school = new MySchool();
school.setId("" + obj.getInt("id"));
school.setName("" + obj.getString("name"));
school.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
school.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_school.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MySchool school : al_school) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
numTxt.setText(school.getName());
LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(school.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
}
private void drawCollegeMarker() {
JsonArrayRequest collegeRequest = new JsonArrayRequest(urlCollege,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyCollege college = new MyCollege();
college.setId("" + obj.getInt("id"));
college.setName("" + obj.getString("name"));
college.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
college.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_college.add(college);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyCollege college : al_college) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_college, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_college);
numTxt.setText(college.getName());
LatLng latlng = new LatLng(college.getLatitude(), college.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(college.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(collegeRequest);
}
private void drawUniversityMarker() {
JsonArrayRequest uniRequest = new JsonArrayRequest(urlUniversity,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyUniversity university = new MyUniversity();
university.setId("" + obj.getInt("id"));
university.setName("" + obj.getString("name"));
university.setLatitude(Double.parseDouble("" + obj.getDouble("latitude")));
university.setLongitude(Double.parseDouble("" + obj.getDouble("longitude")));
al_university.add(university);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for (MyUniversity university : al_university) {
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_university, null);
TextView numTxt = (TextView) marker.findViewById(R.id.txt_university);
numTxt.setText(university.getName());
LatLng latlng = new LatLng(university.getLatitude(), university.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getContext(), marker))).title(university.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(uniRequest);
}
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
GpsLocation class
public class GpsLocation extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
double speed, direction;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsLocation(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// return TODO;
}
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
Log.d("Getting location", "Location found");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(GpsLocation.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public double getSpeed() {
return speed;
}
public double getDirection() {
return direction;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
speed = location.getSpeed();
direction = location.getBearing();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
is it showing ocean location.??
What is the exact issue i am not able to know and how can this be
resolved?
Your coordinates point to sea(check the values load them in browser and see where it points)? If yes the map might be opening in the ocean check your zoom level(zoom out a lot and see any change is there )
If not there is something wrong with your API Key double check that as well.
Further more go through Request runtime permissions
If you want an example check this > https://stackoverflow.com/a/34582595/5188159
I am having two doubts because today only i started doing projects on google maps my first doubt is
How to calculate distance traveled by user when using google maps ?
like how taxi app is calculating the distance, now let me explain my problem in depth regarding this question i have checkin and check out button in map when user click the checkin button i will take that exact lat and long of that user when user checkout i will fetch the lat and long from where he checked out, after i will send this source latlong and destination latlong to google api this will return the kilometer. But what i need is wherever he traveled he may traveled extra bit of kilometer i need to calculate that also how can i do that.
My second doubt is my google maps taking long time to plot the blue mark in my map it shows searching for gps in notification bar how can i achieve this ?
Below is my complete Code
VisitTravel.java
public class VisitTravel extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private List < LatLng > obj;
private GoogleMap mGoogleMap;
private Double latitue, longtitue, Start_lat, Start_long;
private SupportMapFragment mapFrag;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private ImageView cancel_bottomsheet;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private Bundle bundle;
private ProgressDialog progressDialog;
private String Checkin, parsedDistance, duration, JsonResponse;
private VisitDAO visitDAO;
private Long primaryID;
private ArrayList < LatLng > points;
private Integer id, flag, incidentid, userid;
private TextView heading, duration_textview, dot_source, destination, distance;
private PowerManager.WakeLock wakeLock;
private BottomSheetBehavior bottomSheetBehavior;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visit_travel);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
InternetCheck internetCheck = new InternetCheck();
boolean check = internetCheck.isNetworkAvailable(VisitTravel.this);
if (!check) {
showAlertDialog();
} else {
createLocationRequest();
buildGoogleApiClient();
Settingsapi();
progressDialog = new ProgressDialog(VisitTravel.this);
// polylineOptions = new PolylineOptions();
cancel_bottomsheet = (ImageView) findViewById(R.id.cancel);
heading = (TextView) findViewById(R.id.heading);
dot_source = (TextView) findViewById(R.id.dot_source);
distance = (TextView) findViewById(R.id.distance);
duration_textview = (TextView) findViewById(R.id.duration);
destination = (TextView) findViewById(R.id.destination);
progressDialog.setMessage("Fetching Location Updates");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
View bottomSheet = findViewById(R.id.bottom_sheet);
LoginDAO loginobj = new LoginDAO(this);
userid = loginobj.getUserID();
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
cancel_bottomsheet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
bundle = getIntent().getExtras();
if (bundle != null) {
flag = bundle.getInt("flag");
latitue = bundle.getDouble("destination_lat");
longtitue = bundle.getDouble("destination_long");
incidentid = bundle.getInt("incidentid");
if (flag == 1) {
} else {
// time = bundle.getString("checkin");
id = bundle.getInt("id");
incidentid = bundle.getInt("incidentid");
Start_lat = bundle.getDouble("lat");
Checkin = bundle.getString("checkin");
Start_long = bundle.getDouble("long");
String address = bundle.getString("startaddress");
String distance = bundle.getString("estimateddistance");
setBottomSheet(address, distance);
}
}
obj = new ArrayList < > ();
final FloatingActionButton startfab = (FloatingActionButton) findViewById(R.id.start);
final FloatingActionButton stopfab = (FloatingActionButton) findViewById(R.id.stopfab);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WakelockTag");
wakeLock.acquire();
visitDAO = new VisitDAO(getApplicationContext());
if (flag == 2) {
startfab.setVisibility(View.INVISIBLE);
}
startfab.setBackgroundResource(R.drawable.ic_play_circle_outline_black_24dp);
final SharedPreferences preferences = getSharedPreferences("lat_long", Context.MODE_PRIVATE);
startfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
String checkin_to_server = dateFormat.format(new Date());
Date date = null;
try {
date = dateFormat.parse(checkin_to_server);
} catch (ParseException e) {
e.printStackTrace();
}
String checkin_view = dateview.format(date);
double startinglat = mLastLocation.getLatitude();
double startinglong = mLastLocation.getLongitude();
// String addres=address(startinglat,startinglong);
String jsonresponse = null;
try {
jsonresponse = new GetDistance().execute(startinglat, startinglong, 12.951601, 80.184641).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
ParserTask parserTask = new ParserTask();
if (jsonresponse != null) {
Log.d("responsejson", jsonresponse);
parserTask.execute(jsonresponse);
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonresponse);
} catch (JSONException e) {
e.printStackTrace();
}
//Here il save the userlocation in db
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Please Wait Till We Recieve Location Updates", Toast.LENGTH_SHORT).show();
}
}
});
stopfab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mLastLocation != null) {
double lat = mLastLocation.getLatitude();
double longt = mLastLocation.getLongitude();
String startlat = preferences.getString("startlat", "");
Log.d("startlat", startlat);
String startlong = preferences.getString("startlong", "");
// Calculating distance
String distance = getKilometer(Double.valueOf(startlat), Double.valueOf(startlong), lat, longt);
Intent intent = new Intent(VisitTravel.this, IncidentView.class);
setResult(RESULT_OK, intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Please Wait Fetching Location", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onStart() {
super.onStart();
Log.d("start", "onStart fired ..............");
mGoogleApiClient.connect();
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(VisitTravel.this);
builder.setTitle("Network Connectivity")
.setMessage("Please Check Your Network Connectivity")
.setCancelable(false)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), IncidentView.class);
setResult(RESULT_OK, intent);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onPause() {
super.onPause();
// progressDialog.dismiss();
if (wakeLock.isHeld()) {
wakeLock.release();
}
//stop location updates when Activity is no longer active
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map_marker_End(12.951601, 80.184641, "Destination");
if (flag == 2) {
map_marker_start(Start_lat, Start_long, Checkin);
}
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
createLocationRequest();
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)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000 * 10);
mLocationRequest.setFastestInterval(1000 * 5);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
protected void startLocationUpdates() {
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
Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(VisitTravel.this,
new String[] {
android.Manifest.permission
.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
},
20);
} else {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d("Loc", "Location update started ..............: ");
// Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public void map_marker_start(Double lat, Double longt, String title) {
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions.position(latLng);
markerOptions.title(title);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mGoogleMap.addMarker(markerOptions).showInfoWindow();
}
public void map_marker_End(Double lat, Double longt, String title) {
final MarkerOptions markerOptions_end = new MarkerOptions();
LatLng latLng = new LatLng(lat, longt);
Log.d("lat", String.valueOf(latLng.longitude));
markerOptions_end.position(latLng);
markerOptions_end.title(title);
markerOptions_end.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mGoogleMap.addMarker(markerOptions_end).showInfoWindow();
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
if (title.equals("Destination")) {
dot_source.setText("\u2022");
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
heading.setText("TEST");
duration_textview.setText("Duration:" + " " + duration);
return true;
} else {
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
return true;
}
}
});
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
PolylineOptions polylineOptions = new PolylineOptions();
Log.d("location", mLastLocation.toString());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
obj.add(latLng);
polylineOptions.addAll(obj);
polylineOptions.width(9);
polylineOptions.color(Color.parseColor("#2196f3"));
mGoogleMap.addPolyline(polylineOptions);
progressDialog.dismiss();
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
latLng, 12);
mGoogleMap.animateCamera(cameraUpdate);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(VisitTravel.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.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(VisitTravel.this,
new String[] {
android.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[] {
android.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,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
createLocationRequest();
/// buildGoogleApiClient();
// Settingsapi();
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
}
}
public String getKilometer(final double lat1, final double lon1, final double lat2, final double lon2) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader( in ));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
Log.e("empty", "empty");
}
JsonResponse = buffer.toString();
Log.d("response", JsonResponse);
JSONObject jsonObject = new JSONObject(JsonResponse);
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
parsedDistance = distance.getString("text");
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return parsedDistance;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Intent intent = new Intent(this, Incident.class);
startActivity(intent);
break;
}
break;
}
}
#Override
protected void onStop() {
super.onStop();
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, IncidentView.class);
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
setResult(RESULT_OK, intent);
finish();
}
}
Searched alot and not getting proper way to start with? Any help would really valuable.
--Thanks!
This worked for me:
Capture the latitude and longitude at regular intervals and store. Calculate and sum the distance between each stored value.
I am working on a map based application to find out nearby places (like Restaurants, Hospitals, etc) around user's current location. When suppose I click on restaurants, it loads nearby restaurants around users current location correctly in the Google Map. But when I zoom in 2-3 or more times on the map to click on my required marker, it zooms out automatically in some time. I just want to have control in that zoom out event. What can I do to avoid the automatic zooming out thing in map?
Thanks in advance!!
The below class displays the markers and infowindow in the map.
public class PlacesDisplayTask extends AsyncTask<Object, Integer, List<HashMap<String, String>>> {
JSONObject googlePlacesJson;
GoogleMap googleMap;
private int grpId;
private String name;
Context mContext;
private Location location;
Map<LatLng, String> vicinities = new HashMap<LatLng, String>();
ImageView iv;
//Context getContext;
#Override
protected List<HashMap<String, String>> doInBackground(Object... inputObj) {
List<HashMap<String, String>> googlePlacesList = null;
Places placeJsonParser = new Places();
try {
googleMap = (GoogleMap) inputObj[0];
grpId = (Integer)inputObj[2];
mContext = (Context)inputObj[3];
location = (Location)inputObj[4];
name = (String)inputObj[5];
googlePlacesJson = new JSONObject((String) inputObj[1]);
googlePlacesList = placeJsonParser.parse(googlePlacesJson);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return googlePlacesList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
googleMap.clear();
if (list==null){
return;
}
for (int i = 0; i < list.size(); i++) {
final MarkerOptions markerOptions = new MarkerOptions();
final HashMap<String, String> googlePlace = list.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
final LatLng latLng = new LatLng(lat, lng);
final BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(getIcon(grpId));
final String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
vicinities.put(latLng, vicinity);
markerOptions.position(latLng)
.title(placeName)
.icon(icon);
googleMap.addMarker(markerOptions);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.custom_info_window, null);
TextView tv = (TextView)v.findViewById(R.id.tv1);
ImageView iv = (ImageView)v.findViewById(R.id.iv1);
tv.setText(marker.getTitle());
iv.setImageResource(R.drawable.rsz_info);
return v;
}
});
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
});
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent intent = new Intent(mContext, AddressGenerator.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("place_value", marker.getTitle());
intent.putExtra("vicinity_value", vicinities.get(marker.getPosition()));
intent.putExtra("lat_dest", String.valueOf(marker.getPosition().latitude));
intent.putExtra("lng_dest",String.valueOf( marker.getPosition().longitude));
intent.putExtra("lat_src", String.valueOf(location.getLatitude()));
intent.putExtra("lng_src", String.valueOf(location.getLongitude()));
intent.putExtra("name", name);
mContext.startActivity(intent);
}
});
}
}
private int getIcon(int groupId){
int icon = 0;
switch (groupId){
case 0:
icon = R.drawable.rsz_personal_care;
break;
case 1:
icon = R.drawable.rsz_atm;
break;
case 2:
icon = R.drawable.rsz_shopping;
break;
case 3:
icon = R.drawable.rsz_health;
break;
case 4:
icon = R.drawable.rsz_indicator;
break;
case 5:
icon = R.drawable.rsz_petrol;
break;
case 6:
icon = R.drawable.rsz_entertainment;
break;
case 7:
icon = R.drawable.rsz_bar;
break;
case 8:
icon = R.drawable.rsz_service_station;
break;
case 9:
icon = R.drawable.rsz_police;
break;
case 10:
icon = R.drawable.rsz_food;
break;
case 11:
icon = R.drawable.rsz_worship;
break;
}
return icon;
}
}
MapsActivity.class
public class MapsActivity extends AppCompatActivity implements LocationListener {
private GoogleMap googleMap;
private double latitude;
private double longitude;
private int PROXIMITY_RADIUS = 5000;
private String type;
private int grpId;
private String name;
private final static int REQUEST_CODE_FINE_LOCATION = 1;
private final static int REQUEST_CODE_COARSE_LOCATION = 2;
private static final int PERMISSION_REQUEST_CODE = 200;
private static final String GOOGLE_API_KEY = "AIzaSyBEZMt******Jhvct-OXni8mX*******w7GX4Q";
private View view;
LocationManager locationManager;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
view = findViewById(R.id.map_id);
if(checkPermission()){
// Snackbar.make(view, "Permission already granted", Snackbar.LENGTH_LONG).show();
}
else
{
requestPermission();
}
if (!isGooglePlayServicesAvailable()) {
finish();
}
type = getIntent().getStringExtra("type");
grpId = Integer.parseInt(getIntent().getStringExtra("grpId"));
name = getIntent().getStringExtra("name");
googleMap = ((MapFragment) (getFragmentManager().findFragmentById(R.id.map))).getMap();
googleMap.setMyLocationEnabled(true);
LocationListener locationListener = new MyLocationListener();
GPSTracker gpsTracker = new GPSTracker(this);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
gpsTracker.showSettingsAlert();
}
else {
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 20000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("Network", "Network");
if (locationManager != null) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
if (googleMap != null) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=" + type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
GooglePlacesReadTask googlePlacesReadTask = new GooglePlacesReadTask();
Object[] toPass = new Object[6];
toPass[0] = googleMap;
toPass[1] = googlePlacesUrl.toString();
toPass[2] = grpId;
toPass[3] = getApplicationContext();
toPass[4] = location;
toPass[5] = name;
googlePlacesReadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, toPass);
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else
{
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
int result2 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED
&& result2 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}
You are moving (and animating) the camera each time the onLocationChangedis called.
As you are doing:
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
The second line overrides the first one and the effect is that the map is zoomed.
Just remove these lines to avoid the zooming effect.