Getting the phone number of nearby place

2019-07-09 01:53发布

问题:

I've been following this tutorial on displaying nearby places, in my case I need nearby hospitals. I'm able to show my current location and display nearby hospitals. But what I want to do is add the telephone number of those hospitals being displayed. I've tried adding formatted_phone_number in my code but it doesn't display the correct phone number but instead displays "-NA-" which is the default in the event that there's no number available.

Any help would be greatly appreciated thanks!

Code Snippet of GetNearbyPlacesData class:

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");
        String formatted_phone_number = googlePlace.get("formatted_phone_number");
        LatLng latLng = new LatLng(lat, lng);
        markerOptions.position(latLng);
        markerOptions.title(placeName + " : " + vicinity);
        markerOptions.snippet(vicinity + formatted_phone_number);
        mMap.addMarker(markerOptions);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    }
}

DataParser class:

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

    try {
        Log.d("Places", "parse");
        jsonObject = new JSONObject((String) jsonData);
        jsonArray = jsonObject.getJSONArray("results");
    } catch (JSONException e) {
        Log.d("Places", "parse error");
        e.printStackTrace();
    }
    return getPlaces(jsonArray);
}

private List<HashMap<String, String>> getPlaces(JSONArray jsonArray) {
    int placesCount = jsonArray.length();
    List<HashMap<String, String>> placesList = new ArrayList<>();
    HashMap<String, String> placeMap = null;
    Log.d("Places", "getPlaces");

    for (int i = 0; i < placesCount; i++) {
        try {
            placeMap = getPlace((JSONObject) jsonArray.get(i));
            placesList.add(placeMap);
            Log.d("Places", "Adding places");

        } catch (JSONException e) {
            Log.d("Places", "Error in Adding places");
            e.printStackTrace();
        }
    }
    return placesList;
}

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

    Log.d("getPlace", "Entered");

    try {
        if (!googlePlaceJson.isNull("name")) {
            placeName = googlePlaceJson.getString("name");
        }
        if (!googlePlaceJson.isNull("vicinity")) {
            vicinity = googlePlaceJson.getString("vicinity");
        }
        if (!googlePlaceJson.isNull("formatted_phone_number")) {
            formatted_phone_number = googlePlaceJson.getString("formatted_phone_number");
        }
        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("formatted_phone_number", formatted_phone_number);
        googlePlaceMap.put("lat", latitude);
        googlePlaceMap.put("lng", longitude);
        googlePlaceMap.put("reference", reference);
        Log.d("getPlace", "Putting Places");
    } catch (JSONException e) {
        Log.d("getPlace", "Error");
        e.printStackTrace();
    }
    return googlePlaceMap;
    }
}

MapsActivity class:

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

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

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

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

    //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;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

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


    Button btnHospital = (Button) findViewById(R.id.btnHospital);
    btnHospital.setOnClickListener(new View.OnClickListener() {
        String Hospital = "hospital";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Hospital);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Hospitals", 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,
            android.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=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0"); //dito yung api key nasa sticky note
    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(MapsActivity.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,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

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

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

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


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{android.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,
                        android.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.
    }
   }
}

回答1:

In MapsActivity.class, function getUrl() is taking "Hospital" as one of the arguments which is not in the list of supported types. So, the result type is default, since it doesn't match any supported types. The response will give you all the places nearby search request for places of type 'default'. To make a request to Nearby Places API to get nearby hospitals, pass hospital instead of Hospital.

In the code, you make a request to Nearby Places API, formatted_phone_number is not returned in response. For more information, refer to the documentation.

To get the phone number(formatted_phone_number or international_phone_number) make a request to Place Details API with the PlaceId.

To get more clarity, enter the url in the browser and look at the response.

Hope this helps you. Good luck :)