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 ?
Related
I want to get user coordinate, the gps is on , I've asked for permission it has the permissions.
the location is set , I've my locations on other apps like google map but in my application , it doesn't work :
public boolean startService() {
try {
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
return false;
}
}
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();
}
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 FetchCordinates.VeggsterLocationListener mVeggsterLocationListener;
#Override
protected void onPreExecute() {
mVeggsterLocationListener = new FetchCordinates.VeggsterLocationListener();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mVeggsterLocationListener);
a = new AlertDialog.Builder(Admins.this);
a.setMessage("در حال به دست آوردن موقعیت جغرافیایی...");
a.setPositiveButton(("بیخیال"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
FetchCordinates.this.cancel(true);
}
});
dialog = a.show();
TextView messageText = (TextView) dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.RIGHT);
messageText.setTypeface(typeface);
}
#Override
protected void onCancelled() {
System.out.println("Cancelled by user!");
dialog.dismiss();
mLocationManager.removeUpdates(mVeggsterLocationListener);
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.v("this","got the location");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (this.lati == 0.0 && !isCancelled()) {
}
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");
}
}
}
it shows me the dialog for getting the location but it never get the current location .
What's wrong with my code ?
Please provide what you wrote in your Manifest.xml file. Maybe there is something wrong with the permissions.
You need
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
for API 5.0 or higher also:
android.hardware.location.gps
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)));
}
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 want to display Latitude,Longitude of current Location and display the name of the location from that latitude and longitude of that place in three textviews. But latitude and longitude value is not displaying in tv_lat and tv_long.
public class MainActivity extends AppCompatActivity implements NetworkCallback, LocationListener {
private EditText empIdTxt;
private EditText passwordTxt;
private TextView tv_lat;
private TextView tv_long;
private TextView tv_place;
private Button loginBtn;
protected Location mLastLocation;
LocationManager locationmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
empIdTxt = (EditText) findViewById(R.id.et_loginId);
passwordTxt = (EditText) findViewById(R.id.et_loginPass);
tv_lat = (TextView) findViewById(R.id.tv_lat);
tv_long = (TextView) findViewById(R.id.tv_long);
tv_place = (TextView) findViewById(R.id.tv_place);
loginBtn = (Button) findViewById(R.id.bt_login);
empIdTxt.addTextChangedListener(new MyTextWatcher(empIdTxt));
passwordTxt.addTextChangedListener(new MyTextWatcher(passwordTxt));
empIdTxt.setText("vinay");
passwordTxt.setText("qwerty");
locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria cri = new Criteria();
String provider = locationmanager.getBestProvider(cri, false);
if (provider != null & !provider.equals("")) {
Location location = locationmanager.getLastKnownLocation(provider);
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.requestLocationUpdates(provider, 2000, 1, this);
if(location!=null) {
onLocationChanged(location);
}else{
Toast.makeText(getApplicationContext(),"location not found",Toast.LENGTH_LONG ).show();
}
}else{
Toast.makeText(getApplicationContext(),"Provider is null",Toast.LENGTH_LONG).show();
}
}
public void clickLogin(View v) {
if (!validateEmpID()) {
return;
}
if (!validatePassword()) {
return;
}
LoginApi api = new LoginApi(this, this);
api.processLogin(empIdTxt.getText().toString(), passwordTxt.getText().toString(),
mLastLocation.getLatitude()+"",mLastLocation.getLongitude()+"",
AlertDialogManager.todayDate(), new GPSTracker(MainActivity.this).getLocation()+"");
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private boolean validateEmpID() {
if (empIdTxt.getText().toString().trim().isEmpty()) {
empIdTxt.setError(ErrorUtil.USERNAME_ERROR);
requestFocus(empIdTxt);
return false;
}
return true;
}
private boolean validatePassword() {
if (passwordTxt.getText().toString().trim().isEmpty()) {
passwordTxt.setError(ErrorUtil.PASSWORD_ERROR);
requestFocus(passwordTxt);
return false;
}
return true;
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.et_loginId:
validateEmpID();
break;
case R.id.et_loginPass:
validatePassword();
break;
}
}
}
#Override
public void updateScreen(String data, String tag) {
if (tag.compareTo(ApiUtil.TAG_LOGIN) == 0) {
try {
System.out.println("Login Response"+data);
JSONObject mainObj = new JSONObject(data);
AppDelegate ctrl = AppDelegate.getInstance();
if (!mainObj.isNull("username")) {
ctrl.username = mainObj.getString("username");
}
if (!mainObj.isNull("password")) {
ctrl.password = mainObj.getString("password");
}
/* if (!mainObj.isNull("latitude")) {
ctrl.password = mainObj.getString("latitude");
}
if (!mainObj.isNull("longitude")) {
ctrl.password = mainObj.getString("longitude");
}
if (!mainObj.isNull("date_and_time")) {
ctrl.password = mainObj.getString("date_and_time");
}
if (!mainObj.isNull("place")) {
ctrl.password = mainObj.getString("place");
}*/
if (!mainObj.isNull("error")) {
Toast.makeText(MainActivity.this,"Login Fails",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this,"Login Success",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this,"Seems there is an issue please try again later",Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onLocationChanged(Location location) {
tv_lat.setText("Latitude"+location.getLatitude());
tv_long.setText("Longitude"+ location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
Make sure you have given this permission in manifest & your gps should be turned on:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In case if you are testing your application in marshmallow:
Give permissions programmatically.
Last thing is remove this condition from your code and run it. It will definitely work:
Remove this:
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;
}
If you find it is not working, I post my own class which is working perfect on Lollipop check it:
public class Google_Map_Current_Location extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.google_map_current_loction);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
try {
googleMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsAlert();
}
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
try {
location = locationManager.getLastKnownLocation(bestProvider);
} catch (Exception e) {
e.printStackTrace();
}
if (location != null) {
onLocationChanged(location);
}
try {
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// 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);
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();
}
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