Unable to find nearby places from current location












0














I'm developing app in which I've implemented Google Map. Finding current location is done successfully. Now I want to show nearby places at current location for example when I click find button it should show all "Restaurants" near the current location. But when I press find button nothing happens and current location marker dismisses just a blue circle stays on current location.



Please help I'm stuck.



Following APIs are enabled on my API key



1) Maps SDK for Android



2) Places API



3) Places SDK for Android



enter image description here



My code:
DataParser.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DataParser {
private HashMap<String, String> getPlace(JSONObject googlePlaceJson)
{
HashMap<String, String> googlePlaceMap = new HashMap<>();
String placeName = "--NA--";
String vicinity= "--NA--";
String latitude= "";
String longitude="";
String reference="";

Log.d("DataParser","jsonobject ="+googlePlaceJson.toString());


try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}

latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");

reference = googlePlaceJson.getString("reference");

googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);


}
catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;

}
private List<HashMap<String, String>>getPlaces(JSONArray jsonArray)
{
int count = jsonArray.length();
List<HashMap<String, String>> placelist = new ArrayList<>();
HashMap<String, String> placeMap = null;

for(int i = 0; i<count;i++)
{
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placelist.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placelist;
}

public List<HashMap<String, String>> parse(String jsonData)
{
JSONArray jsonArray = null;
JSONObject jsonObject;

Log.d("json data", jsonData);

try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}


DownloadURL.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadURL {

public String readUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}

data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();

} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}


GetNearbPlacesData.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

String googlePlacesData;
GoogleMap mMap;
String url;

@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadURL downloadUrl = new DownloadURL();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}

@Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}

private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}


NearMosquesActivity.java



package com.blogspot.atifsoftwares.emguider.NearMosques;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.blogspot.atifsoftwares.emguider.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;

public class NearMosquesActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {

private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_mosques);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}

//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}


/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

Button btnRestaurant = (Button) findViewById(R.id.findMosqueBtn);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
@Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(NearMosquesActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});


}

protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

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("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAoRY0tBFcq_5lgsdIfdQQLRZcEYsicICw");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(NearMosquesActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);


} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}

} else {

// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
}









share|improve this question
























  • Display url in toast to check what url are you getting...
    – Atif Pervaiz
    Nov 24 '18 at 7:48










  • I've added screenshot of the url got in toast when I click find button
    – Hasnain Jutt
    Nov 24 '18 at 9:01
















0














I'm developing app in which I've implemented Google Map. Finding current location is done successfully. Now I want to show nearby places at current location for example when I click find button it should show all "Restaurants" near the current location. But when I press find button nothing happens and current location marker dismisses just a blue circle stays on current location.



Please help I'm stuck.



Following APIs are enabled on my API key



1) Maps SDK for Android



2) Places API



3) Places SDK for Android



enter image description here



My code:
DataParser.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DataParser {
private HashMap<String, String> getPlace(JSONObject googlePlaceJson)
{
HashMap<String, String> googlePlaceMap = new HashMap<>();
String placeName = "--NA--";
String vicinity= "--NA--";
String latitude= "";
String longitude="";
String reference="";

Log.d("DataParser","jsonobject ="+googlePlaceJson.toString());


try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}

latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");

reference = googlePlaceJson.getString("reference");

googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);


}
catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;

}
private List<HashMap<String, String>>getPlaces(JSONArray jsonArray)
{
int count = jsonArray.length();
List<HashMap<String, String>> placelist = new ArrayList<>();
HashMap<String, String> placeMap = null;

for(int i = 0; i<count;i++)
{
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placelist.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placelist;
}

public List<HashMap<String, String>> parse(String jsonData)
{
JSONArray jsonArray = null;
JSONObject jsonObject;

Log.d("json data", jsonData);

try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}


DownloadURL.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadURL {

public String readUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}

data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();

} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}


GetNearbPlacesData.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

String googlePlacesData;
GoogleMap mMap;
String url;

@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadURL downloadUrl = new DownloadURL();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}

@Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}

private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}


NearMosquesActivity.java



package com.blogspot.atifsoftwares.emguider.NearMosques;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.blogspot.atifsoftwares.emguider.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;

public class NearMosquesActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {

private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_mosques);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}

//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}


/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

Button btnRestaurant = (Button) findViewById(R.id.findMosqueBtn);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
@Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(NearMosquesActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});


}

protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

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("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAoRY0tBFcq_5lgsdIfdQQLRZcEYsicICw");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(NearMosquesActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);


} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}

} else {

// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
}









share|improve this question
























  • Display url in toast to check what url are you getting...
    – Atif Pervaiz
    Nov 24 '18 at 7:48










  • I've added screenshot of the url got in toast when I click find button
    – Hasnain Jutt
    Nov 24 '18 at 9:01














0












0








0







I'm developing app in which I've implemented Google Map. Finding current location is done successfully. Now I want to show nearby places at current location for example when I click find button it should show all "Restaurants" near the current location. But when I press find button nothing happens and current location marker dismisses just a blue circle stays on current location.



Please help I'm stuck.



Following APIs are enabled on my API key



1) Maps SDK for Android



2) Places API



3) Places SDK for Android



enter image description here



My code:
DataParser.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DataParser {
private HashMap<String, String> getPlace(JSONObject googlePlaceJson)
{
HashMap<String, String> googlePlaceMap = new HashMap<>();
String placeName = "--NA--";
String vicinity= "--NA--";
String latitude= "";
String longitude="";
String reference="";

Log.d("DataParser","jsonobject ="+googlePlaceJson.toString());


try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}

latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");

reference = googlePlaceJson.getString("reference");

googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);


}
catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;

}
private List<HashMap<String, String>>getPlaces(JSONArray jsonArray)
{
int count = jsonArray.length();
List<HashMap<String, String>> placelist = new ArrayList<>();
HashMap<String, String> placeMap = null;

for(int i = 0; i<count;i++)
{
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placelist.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placelist;
}

public List<HashMap<String, String>> parse(String jsonData)
{
JSONArray jsonArray = null;
JSONObject jsonObject;

Log.d("json data", jsonData);

try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}


DownloadURL.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadURL {

public String readUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}

data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();

} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}


GetNearbPlacesData.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

String googlePlacesData;
GoogleMap mMap;
String url;

@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadURL downloadUrl = new DownloadURL();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}

@Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}

private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}


NearMosquesActivity.java



package com.blogspot.atifsoftwares.emguider.NearMosques;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.blogspot.atifsoftwares.emguider.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;

public class NearMosquesActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {

private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_mosques);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}

//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}


/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

Button btnRestaurant = (Button) findViewById(R.id.findMosqueBtn);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
@Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(NearMosquesActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});


}

protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

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("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAoRY0tBFcq_5lgsdIfdQQLRZcEYsicICw");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(NearMosquesActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);


} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}

} else {

// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
}









share|improve this question















I'm developing app in which I've implemented Google Map. Finding current location is done successfully. Now I want to show nearby places at current location for example when I click find button it should show all "Restaurants" near the current location. But when I press find button nothing happens and current location marker dismisses just a blue circle stays on current location.



Please help I'm stuck.



Following APIs are enabled on my API key



1) Maps SDK for Android



2) Places API



3) Places SDK for Android



enter image description here



My code:
DataParser.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DataParser {
private HashMap<String, String> getPlace(JSONObject googlePlaceJson)
{
HashMap<String, String> googlePlaceMap = new HashMap<>();
String placeName = "--NA--";
String vicinity= "--NA--";
String latitude= "";
String longitude="";
String reference="";

Log.d("DataParser","jsonobject ="+googlePlaceJson.toString());


try {
if (!googlePlaceJson.isNull("name")) {
placeName = googlePlaceJson.getString("name");
}
if (!googlePlaceJson.isNull("vicinity")) {
vicinity = googlePlaceJson.getString("vicinity");
}

latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");

reference = googlePlaceJson.getString("reference");

googlePlaceMap.put("place_name", placeName);
googlePlaceMap.put("vicinity", vicinity);
googlePlaceMap.put("lat", latitude);
googlePlaceMap.put("lng", longitude);
googlePlaceMap.put("reference", reference);


}
catch (JSONException e) {
e.printStackTrace();
}
return googlePlaceMap;

}
private List<HashMap<String, String>>getPlaces(JSONArray jsonArray)
{
int count = jsonArray.length();
List<HashMap<String, String>> placelist = new ArrayList<>();
HashMap<String, String> placeMap = null;

for(int i = 0; i<count;i++)
{
try {
placeMap = getPlace((JSONObject) jsonArray.get(i));
placelist.add(placeMap);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placelist;
}

public List<HashMap<String, String>> parse(String jsonData)
{
JSONArray jsonArray = null;
JSONObject jsonObject;

Log.d("json data", jsonData);

try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
return getPlaces(jsonArray);
}
}


DownloadURL.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownloadURL {

public String readUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}

data = sb.toString();
Log.d("downloadUrl", data.toString());
br.close();

} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}


GetNearbPlacesData.java



package com.blogspot.atifsoftwares.emguider.NearMosques;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

String googlePlacesData;
GoogleMap mMap;
String url;

@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadURL downloadUrl = new DownloadURL();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}

@Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}

private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
for (int i = 0; i < nearbyPlacesList.size(); i++) {
Log.d("onPostExecute","Entered into showing locations");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
double lat = Double.parseDouble(googlePlace.get("lat"));
double lng = Double.parseDouble(googlePlace.get("lng"));
String placeName = googlePlace.get("place_name");
String vicinity = googlePlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName + " : " + vicinity);
mMap.addMarker(markerOptions);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
}
}


NearMosquesActivity.java



package com.blogspot.atifsoftwares.emguider.NearMosques;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.blogspot.atifsoftwares.emguider.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;

public class NearMosquesActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {

private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_mosques);

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}

//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}

// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}


/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

Button btnRestaurant = (Button) findViewById(R.id.findMosqueBtn);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
@Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(NearMosquesActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});


}

protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}

private String getUrl(double latitude, double longitude, String nearbyPlace) {

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("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyAoRY0tBFcq_5lgsdIfdQQLRZcEYsicICw");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");

mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}

//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);

//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(NearMosquesActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();

Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));

//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {

// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);


} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions, int grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {

if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}

} else {

// Permission denied, 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.
// You can add here other case statements according to your requirement.
}
}
}






android google-maps






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 9:00

























asked Nov 23 '18 at 4:51









Hasnain Jutt

114




114












  • Display url in toast to check what url are you getting...
    – Atif Pervaiz
    Nov 24 '18 at 7:48










  • I've added screenshot of the url got in toast when I click find button
    – Hasnain Jutt
    Nov 24 '18 at 9:01


















  • Display url in toast to check what url are you getting...
    – Atif Pervaiz
    Nov 24 '18 at 7:48










  • I've added screenshot of the url got in toast when I click find button
    – Hasnain Jutt
    Nov 24 '18 at 9:01
















Display url in toast to check what url are you getting...
– Atif Pervaiz
Nov 24 '18 at 7:48




Display url in toast to check what url are you getting...
– Atif Pervaiz
Nov 24 '18 at 7:48












I've added screenshot of the url got in toast when I click find button
– Hasnain Jutt
Nov 24 '18 at 9:01




I've added screenshot of the url got in toast when I click find button
– Hasnain Jutt
Nov 24 '18 at 9:01

















active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440807%2funable-to-find-nearby-places-from-current-location%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440807%2funable-to-find-nearby-places-from-current-location%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

What visual should I use to simply compare current year value vs last year in Power BI desktop

How to ignore python UserWarning in pytest?

Alexandru Averescu