Android 获取附近地方的电话号码

Android 获取附近地方的电话号码,android,google-maps,google-places-api,Android,Google Maps,Google Places Api,我一直在遵循本教程,展示附近的地方,在我的情况下,我需要附近的医院。我可以显示我的当前位置和附近的医院。但我想做的是添加显示的医院的电话号码。我尝试在我的代码中添加格式化的电话号码,但它不会显示正确的电话号码,而是显示“-NA-”,这是在没有可用号码的情况下的默认设置 任何帮助都将不胜感激,谢谢 GetNearbyPlacesData类的代码段: private void ShowNearbyPlaces(List<HashMap<String, String>> nea

我一直在遵循本教程,展示附近的地方,在我的情况下,我需要附近的医院。我可以显示我的当前位置和附近的医院。但我想做的是添加显示的医院的电话号码。我尝试在我的代码中添加
格式化的电话号码
,但它不会显示正确的电话号码,而是显示“-NA-”,这是在没有可用号码的情况下的默认设置

任何帮助都将不胜感激,谢谢

GetNearbyPlacesData类的代码段:

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

在MapsActivity.class中,函数getUrl()将“Hospital”作为参数之一,该参数不在参数列表中。因此,结果类型是默认的,因为它不匹配任何支持的类型。 该响应将为您提供“默认”类型的所有位置搜索请求。要向附近地点API发出请求以获取附近医院,请通过医院而不是医院

在代码中,您向附近的地方发出请求API,格式化的电话号码不会在响应中返回。有关更多信息,请参阅

要获取电话号码(格式化电话号码或国际电话号码),请使用PlaceId向发出请求

为了更清晰,请在浏览器中输入url并查看响应


希望这对你有帮助。祝你好运:)

你能确认谷歌的回复显示有返回的电话号码吗?例如,
格式化电话号码
国际电话号码
@Bangsi我试过在谷歌地图上查,医院里有电话号码。@Bangsi我已经试过使用
格式化电话号码
国际电话号码
,但仍然没有结果。@Gelly你能告诉我你遵循了哪一个教程吗。@cammando这是一个关于展示附近地方的教程
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;
    }
}
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.
    }
   }
}