简体   繁体   English

Google地图附近的地方仅显示吐司

[英]Google Maps Nearby Places shows only Toasts

I'm working on a final year project and downloaded this code it was working but now I can't understand why it stops working it shows only Toasts, maybe a problem with API key can you help me please. 我正在做一个最后一年的项目,并下载了该代码,它可以正常工作,但是现在我不明白为什么它停止工作,它只显示Toasts,也许API密钥有问题可以帮助我。

public class MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMarkerDragListener { 公共类MapActivity扩展FragmentActivity实现了OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener,GoogleMap.OnMarkerClickListener,GoogleMap.OnMarkerDragListener {

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

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

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





}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater= getMenuInflater();
    menuInflater.inflate(R.menu.menu_item_maps, menu);


    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Object dataTransfer[] = new Object[2];
    GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();

    switch (item.getItemId()){
        case R.id.map_menuitemresto:
            mMap.clear();
            dataTransfer = new Object[2];
            String restaurant = "restaurant";
            String url = getUrl(latitude, longitude, restaurant);
            getNearbyPlacesData = new GetNearbyPlacesData();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;

            getNearbyPlacesData.execute(dataTransfer);
            Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
            break;
    }
    return super.onOptionsItemSelected(item);
}

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;

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

    mMap.setOnMarkerDragListener(this);
    mMap.setOnMarkerClickListener(this);

}



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

public void onClick(View v)
{
    Object dataTransfer[] = new Object[2];
    GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();


    switch(v.getId()) {
        case R.id.B_search: {
            EditText tf_location = (EditText) findViewById(R.id.TF_location);
            String location = tf_location.getText().toString();
            List<Address> addressList = null;
            MarkerOptions markerOptions = new MarkerOptions();
            Log.d("location = ", location);

            if (!location.equals("")) {
                Geocoder geocoder = new Geocoder(this);
                try {
                    addressList = geocoder.getFromLocationName(location, 5);

                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (addressList != null) {
                    for (int i = 0; i < addressList.size(); i++) {
                        Address myAddress = addressList.get(i);
                        LatLng latLng = new LatLng(myAddress.getLatitude(), myAddress.getLongitude());
                        markerOptions.position(latLng);
                        mMap.addMarker(markerOptions);
                        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                    }
                }

            }
        }
        break;
        case R.id.B_hotels:
            //mMap.clear();
            String hospital = "hotel";
            String url = getUrl(latitude, longitude, hospital);
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;

            getNearbyPlacesData.execute(dataTransfer);
            Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
            break;

        case R.id.B_restaurant:
            //mMap.clear();
            dataTransfer = new Object[2];
            String restaurant = "restaurant";
            url = getUrl(latitude, longitude, restaurant);
            getNearbyPlacesData = new GetNearbyPlacesData();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;

            getNearbyPlacesData.execute(dataTransfer);
            Toast.makeText(MapActivity.this, "Showing Nearby Restaurants", Toast.LENGTH_LONG).show();
            break;
        case R.id.B_diver:
            //mMap.clear();
            String school = "hotel";
            dataTransfer = new Object[2];
            url = getUrl(latitude, longitude, school);
            getNearbyPlacesData = new GetNearbyPlacesData();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;

            getNearbyPlacesData.execute(dataTransfer);
            Toast.makeText(MapActivity.this, "Showing Nearby Hotels", Toast.LENGTH_LONG).show();
            break;

        case R.id.B_to:
            dataTransfer = new Object[3];
            url = getDirectionsUrl();
            GetDirectionsData getDirectionsData = new GetDirectionsData();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;
            dataTransfer[2] = new LatLng(end_latitude, end_longitude);
            getDirectionsData.execute(dataTransfer);

            break;


    }
}

private String getDirectionsUrl()
{
    StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
    googleDirectionsUrl.append("origin="+latitude+","+longitude);
    googleDirectionsUrl.append("&destination="+end_latitude+","+end_longitude);
    googleDirectionsUrl.append("&key="+"AIzaSyBH5BAD65au_keEdICl_7KFxUzfT8OheVY");

    return googleDirectionsUrl.toString();
}

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=" + "AIzaSyDN7RJFmImYAca96elyZlE5s_fhX-MMuhk");
    Log.d("getUrl", googlePlacesUrl.toString());
    return (googlePlacesUrl.toString());
}




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



@Override
public void onConnectionSuspended(int i) {

}

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

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

    latitude = location.getLatitude();
    longitude = location.getLongitude();


    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.draggable(true);
    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(MapActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();


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

}

@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.
    }
}


@Override
public boolean onMarkerClick(Marker marker) {
    marker.setDraggable(true);
    return false;
}

@Override
public void onMarkerDragStart(Marker marker) {

}

@Override
public void onMarkerDrag(Marker marker) {

}

@Override
public void onMarkerDragEnd(Marker marker) {
    end_latitude = marker.getPosition().latitude;
    end_longitude =  marker.getPosition().longitude;

    Log.d("end_lat",""+end_latitude);
    Log.d("end_lng",""+end_longitude);
}

public void changeTypeMap(View view) {
    if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    } else
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}

} }

I have a button to show nearby places with onClickListener But this will not filter the places 我有一个按钮可以使用onClickListener显示附近的地方,但这不会过滤这些地方

private static final String TAG = "MapActivity";

private static final int PLACE_PICKER_REQUEST = 1;

YOUR_BUTTON = (Button) findViewById(R.id.YOUR_BUTTON_ID)

YOUR_BUTTON.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

     PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

     try {
        startActivityForResult(builder.build(MapActivity.this), PLACE_PICKER_REQUEST);
     } catch (GooglePlayServicesRepairableException e) {
        Log.e(TAG, "onClick: Repairable: " + e.getMessage() );
     } catch (GooglePlayServicesNotAvailableException e) {
        Log.e(TAG, "onClick: NotAvailable: " + e.getMessage() );
     }
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM