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

时间:2015-11-19 06:34:44

标签: java android google-maps google-places-api

我正在创建一个Android应用程序,每当用户选择导航抽屉内的诊所选项时,他/她将被重定向到应用程序地图(使用谷歌地图api键),这将显示他/她当前位置和所有附近的诊所/医院,地图底部有一个清单。

我试图实现但未成功。我知道在SO上有很多这样的问题,但没有一个能满足我的需求。

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

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

Place.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 + '}';
}

PlacesServices.java

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

我能够获取当前位置,但将附近的搜索限制在医院,并且没有发现附近医院的详细信息列表。

请有人帮我解决这个问题。

谢谢

0 个答案:

没有答案