Java 如何在android中使用谷歌地图根据当前位置限制附近位置搜索?

Java 如何在android中使用谷歌地图根据当前位置限制附近位置搜索?,java,android,google-maps,google-places-api,Java,Android,Google Maps,Google Places Api,我正在制作一个android应用程序,每当用户在导航抽屉中选择诊所选项时,他/她将被重定向到应用程序内地图(使用谷歌地图api键),该地图将显示他/她当前的位置和附近所有诊所/医院,并在地图底部列出一个列表 我曾试图实现这一点,但没有成功。我知道有很多这样的问题,但没有一个能满足我的需要 这是我的ClinicFragmentjava文件,我想在其中显示包含所有服务的地图和附近医院的列表 public class ClinicFragment extends FragmentActivity im

我正在制作一个android应用程序,每当用户在导航抽屉中选择诊所选项时,他/她将被重定向到应用程序内地图(使用谷歌地图api键),该地图将显示他/她当前的位置和附近所有诊所/医院,并在地图底部列出一个列表

我曾试图实现这一点,但没有成功。我知道有很多这样的问题,但没有一个能满足我的需要

这是我的ClinicFragmentjava文件,我想在其中显示包含所有服务的地图和附近医院的列表

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

public static final String TAG = ClinicFragment.class.getSimpleName();

/*
 * Define a request code to send to Google Play services
 * This code is returned in Activity.onActivityResult
 */
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;



private GoogleMap mMap; // Might be null if Google Play services APK is not available.

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;

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

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .addApi(LocationServices.API)
            .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

    new GetPlaces(this, getListView()).execute();
}



@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();

    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}


private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}


private void setUpMap() {
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());

    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();

    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setRotateGesturesEnabled(true);
}

@Override
public void onConnected(Bundle bundle) {
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        handleNewLocation(location);
    }
}



@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {
            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
        Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
}




class GetPlaces extends AsyncTask<Void, Void, Void> {

    private ProgressDialog dialog;
    private Context context;
    private String[] placeName;
    private String[] imageUrl;
    private ListView listView;

    public GetPlaces(Context context, ListView listView) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.listView = listView;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        dialog.dismiss();

        listView.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_expandable_list_item_1,placeName));
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setCancelable(true);
        dialog.setMessage("Loading..");
        dialog.isIndeterminate();
        dialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        PlacesServices service = new PlacesServices("paste your place api key");
        List<Place> findPlaces = service.findPlaces(28.632808,77.218276,"hospital");  // hospiral for hospital
        // atm for ATM

        placeName = new String[findPlaces.size()];
        imageUrl = new String[findPlaces.size()];

        for (int i = 0; i < findPlaces.size(); i++) {

            Place placeDetail = findPlaces.get(i);
            placeDetail.getIcon();

            System.out.println(  placeDetail.getName());
            placeName[i] =placeDetail.getName();

            imageUrl[i] =placeDetail.getIcon();

        }
        return null;
    }
}
PlacesServices.java

public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getIcon() {
    return icon;
}

public void setIcon(String icon) {
    this.icon = icon;
}

public Double getLatitude() {
    return latitude;
}

public void setLatitude(Double latitude) {
    this.latitude = latitude;
}

public Double getLongitude() {
    return longitude;
}

public void setLongitude(Double longitude) {
    this.longitude = longitude;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getVicinity() {
    return vicinity;
}

public void setVicinity(String vicinity) {
    this.vicinity = vicinity;
}

static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
    try {
        Place result = new Place();
        JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
        JSONObject location = (JSONObject) geometry.get("location");
        result.setLatitude((Double) location.get("lat"));
        result.setLongitude((Double) location.get("lng"));
        result.setIcon(pontoReferencia.getString("icon"));
        result.setName(pontoReferencia.getString("name"));
        result.setVicinity(pontoReferencia.getString("vicinity"));
        result.setId(pontoReferencia.getString("id"));
        return result;
    } catch (JSONException ex) {
        Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

@Override
public String toString() {
    return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}
public class PlacesServices {

private String API_KEY;

public PlacesServices(String apikey) {
    this.API_KEY = apikey;
}

public void setApiKey(String apikey) {
    this.API_KEY = apikey;
}

public List<Place> findPlaces(double latitude, double longitude,String placeSpacification)
{

    String urlString = makeUrl(latitude, longitude,placeSpacification);


    try {
        String json = getJSON(urlString);

        System.out.println(json);
        JSONObject object = new JSONObject(json);
        JSONArray array = object.getJSONArray("results");


        ArrayList<Place> arrayList = new ArrayList<Place>();
        for (int i = 0; i < array.length(); i++) {
            try {
                Place place = Place.jsonToPontoReferencia((JSONObject) array.get(i));

                Log.v("Places Services ", "" + place);


                arrayList.add(place);
            } catch (Exception e) {
            }
        }
        return arrayList;
    } catch (JSONException ex) {
        Logger.getLogger(PlacesServices.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
//https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=apikey
private String makeUrl(double latitude, double longitude,String place) {
    StringBuilder urlString = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");

    if (place.equals("")) {
        urlString.append("&location=");
        urlString.append(Double.toString(latitude));
        urlString.append(",");
        urlString.append(Double.toString(longitude));
        urlString.append("&radius=1000");
        //   urlString.append("&types="+place);
        urlString.append("&sensor=false&key=" + API_KEY);
    } else {
        urlString.append("&location=");
        urlString.append(Double.toString(latitude));
        urlString.append(",");
        urlString.append(Double.toString(longitude));
        urlString.append("&radius=1000");
        urlString.append("&types="+place);
        urlString.append("&sensor=false&key=" + API_KEY);
    }


    return urlString.toString();
}

protected String getJSON(String url) {
    return getUrlContents(url);
}

private String getUrlContents(String theUrl)
{
    StringBuilder content = new StringBuilder();

    try {
        URL url = new URL(theUrl);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
        String line;
        while ((line = bufferedReader.readLine()) != null)
        {
            content.append(line + "\n");
        }

        bufferedReader.close();
    }

    catch (Exception e)
    {

        e.printStackTrace();

    }

    return content.toString();
}
公共类放置服务{
私有字符串API_密钥;
公共场所服务(字符串apikey){
this.API_KEY=apikey;
}
public void setApiKey(字符串apikey){
this.API_KEY=apikey;
}
公共列表查找位置(双纬度、双经度、字符串位置指定)
{
字符串urlString=makeUrl(纬度、经度、地点指定);
试一试{
String json=getJSON(urlString);
System.out.println(json);
JSONObject对象=新的JSONObject(json);
JSONArray数组=object.getJSONArray(“结果”);
ArrayList ArrayList=新的ArrayList();
对于(int i=0;i
我能够获得当前位置,但将附近的搜索限制在医院,无法获得附近医院的详细信息列表

请任何人帮我解决这个问题


谢谢你

你需要在这里指定
类型
界限
:@KayAnn你试过这个吗?我问这个是因为如果你试过这个[请你给我提供一些教程链接。这样我就很容易理解了,因为我已经在这上面浪费了很多时间。你看:@KayAnn我已经尝试了这个代码,但它不起作用。Thanks@KayAnnRequestLocationUpdate(提供程序,20000,0,this);始终显示空指针异常