我的Android出租车应用程序之一在从地图请求乘车时收到错误消息。我可以指出接送地点,然后进行骑行计算,显示“无效距离,该API项目无权使用此API” 。因为我为Android启用了Google Map,为Android和Google Direction API启用了Google Place。但仍然出现相同的错误。甚至我试图从Google Map启用所有其他17个api,但仍然遇到相同的问题。
任何人都可以解决这个问题吗?
AndroidManifest.xml
<application
android:name="com.prinsapps.vanittcustomer.custom.MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_icon"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:windowSoftInputMode="stateHidden|adjustResize">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_android_map_api_key" />
<activity android:name="com.prinsapps.vanittcustomer.acitivities.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.prinsapps.vanittcustomer.acitivities.LoginActivity"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.prinsapps.vanittcustomer.acitivities.RegisterActivity"
android:windowSoftInputMode="stateHidden" />
<activity android:name="com.prinsapps.vanittcustomer.acitivities.HomeActivity" />
<service
android:name="com.paypal.android.sdk.payments.PayPalService"
android:exported="false" />
<activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
<activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
<activity android:name="com.paypal.android.sdk.payments.PayPalFuturePaymentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentConsentActivity" />
<activity android:name="com.paypal.android.sdk.payments.FuturePaymentInfoActivity" />
<activity android:name="io.card.payment.DataEntryActivity" />
RequestFragment.java
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
networkAvailable = getResources().getString(R.string.network);
tryAgain = getResources().getString(R.string.try_again);
directionRequest = getResources().getString(R.string.direction_request);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.request_ride, container, false);
if (!CheckConnection.haveNetworkConnection(getActivity())) {
Toast.makeText(getActivity(), networkAvailable, Toast.LENGTH_LONG).show();
}
bindView(savedInstanceState);
confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!CheckConnection.haveNetworkConnection(getActivity())) {
Toast.makeText(getActivity(), networkAvailable, Toast.LENGTH_LONG).show();
} else {
if (distance == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_distance), Toast.LENGTH_LONG).show();
} else if (pickup_address == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_pickupaddress), Toast.LENGTH_SHORT).show();
} else if (drop_address == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_dropaddress), Toast.LENGTH_SHORT).show();
} else if (fare == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_fare), Toast.LENGTH_SHORT).show();
} else if (origin == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_pickuplocation), Toast.LENGTH_SHORT).show();
} else if (destination == null) {
Toast.makeText(getActivity(), getString(R.string.invalid_droplocation), Toast.LENGTH_SHORT).show();
} else {
String o = origin.latitude + "," + origin.longitude;
String d = destination.latitude + "," + destination.longitude;
AddRide(SessionManager.getInstance().getKEY(), pickup_address, drop_address, o, d, String.valueOf(finalfare), distance);
}
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), HomeActivity.class));
}
});
return view;
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
getActivity().stopService(new Intent(getActivity(), PayPalService.class));
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
public void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
public void bindView(Bundle savedInstanceState) {
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.ride_request));
//((HomeActivity) getActivity()).toolbar.setTitle(getString(R.string.request_ride));
mapView = (MapView) view.findViewById(R.id.mapview);
calculateFare = (TextView) view.findViewById(R.id.txt_calfare);
confirm = (AppCompatButton) view.findViewById(R.id.btn_confirm);
cancel = (AppCompatButton) view.findViewById(R.id.btn_cancel);
pickup_location = (TextView) view.findViewById(R.id.txt_pickup);
drop_location = (TextView) view.findViewById(R.id.txt_drop);
textView1 = (TextView) view.findViewById(R.id.textView1);
textView2 = (TextView) view.findViewById(R.id.textView2);
textView3 = (TextView) view.findViewById(R.id.textView3);
textView4 = (TextView) view.findViewById(R.id.textView4);
textView5 = (TextView) view.findViewById(R.id.textView5);
txt_name = (TextView) view.findViewById(R.id.txt_name);
txt_number = (TextView) view.findViewById(R.id.txt_number);
txt_fare = (TextView) view.findViewById(R.id.txt_fare);
txt_vehiclename = (TextView) view.findViewById(R.id.txt_vehiclename);
title = (TextView) view.findViewById(R.id.title);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
Typeface book = Typeface.createFromAsset(getContext().getAssets(), "font/AvenirLTStd_Book.otf");
title.setTypeface(book);
cancel.setTypeface(book);
confirm.setTypeface(book);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
Bundle bundle = getArguments();
pass = new Pass();
if (bundle != null) {
pass = (Pass) bundle.getSerializable("data");
if (pass != null) {
origin = pass.getFromPlace().getLatLng();
destination = pass.getToPlace().getLatLng();
driver_id = pass.getDriverId();
fare = Double.valueOf(pass.getFare());
drivername = pass.getDriverName();
pickup_address = pass.getFromPlace().getAddress().toString();
drop_address = pass.getToPlace().getAddress().toString();
if (drivername != null) {
txt_name.setText(drivername);
}
pickup_location.setText(pickup_address);
drop_location.setText(drop_address);
txt_vehiclename.setText(pass.getVehicleName() + "");
}
}
overrideFonts(getActivity(), view);
user_id = SessionManager.getInstance().getUid();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onDirectionSuccess(Direction direction, String rawBody) {
if (getActivity() != null) {
if (direction.isOK()) {
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
myMap.addPolyline(DirectionConverter.createPolyline(getActivity(), directionPositionList, 5, Color.RED));
myMap.addMarker(new MarkerOptions().position(new LatLng(origin.latitude, origin.longitude)).title("Pickup Location").snippet(pickup_address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
myMap.addMarker(new MarkerOptions().position(new LatLng(destination.latitude, destination.longitude)).title("Drop Location").snippet(drop_address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 10));
calculateDistance(Double.valueOf(direction.getRouteList().get(0).getLegList().get(0).getDistance().getValue()) / 1000);
} else {
distanceAlert(direction.getErrorMessage());
//calculateFare.setVisibility(View.GONE);
dismiss();
}
}
}
@Override
public void onDirectionFailure(Throwable t) {
distanceAlert(t.getMessage() + "\n" + t.getLocalizedMessage() + "\n");
// calculateFare.setVisibility(View.GONE);
dismiss();
}
@Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
requestDirection();
}
public void requestDirection() {
snackbar = Snackbar.make(view, getString(R.string.fare_calculating), Snackbar.LENGTH_INDEFINITE);
snackbar.show();
GoogleDirection.withServerKey(getString(R.string.google_api_key))
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(this);
confirm.setEnabled(false);
}
private void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font/AvenirLTStd_Medium.otf"));
}
} catch (Exception e) {
}
}
public void AddRide(String key, String pickup_adress, String drop_address, String pickup_location, String drop_locatoin, String amount, String distance) {
final RequestParams params = new RequestParams();
params.put("driver_id", driver_id);
params.put("user_id", user_id);
params.put("pickup_adress", pickup_adress);
params.put("drop_address", drop_address);
params.put("pikup_location", pickup_location);
params.put("drop_locatoin", drop_locatoin);
params.put("amount", amount);
params.put("distance", distance);
Server.setHeader(key);
Server.post("api/user/addRide/format/json", params, new JsonHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
swipeRefreshLayout.setRefreshing(true);
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
try {
if (response.has("status") && response.getString("status").equalsIgnoreCase("success")) {
Toast.makeText(getActivity(), getString(R.string.ride_has_been_requested), Toast.LENGTH_LONG).show();
((HomeActivity) getActivity()).changeFragment(new HomeFragment(), "Home");
} else {
Toast.makeText(getActivity(), tryAgain, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), tryAgain, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toast.makeText(getActivity(), getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
}
@Override
public void onFinish() {
super.onFinish();
if (getActivity() != null) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
}
public void calculateDistance(Double aDouble) {
distance = String.valueOf(aDouble);
if (aDouble != null) {
if (fare != null && fare != 0.0) {
DecimalFormat dtime = new DecimalFormat("##.##");
Double ff = aDouble * fare;
try {
if (dtime.format(ff).contains(",")) {
String value = dtime.format(ff).replaceAll(",", ".");
finalfare = Double.valueOf(value);
} else {
finalfare = Double.valueOf(dtime.format(ff));
}
dismiss();
} catch (Exception e) {
}
txt_fare.setText(finalfare + " " + SessionManager.getInstance().getUnit());
} else {
txt_fare.setText(SessionManager.getInstance().getUnit());
}
}
confirm.setEnabled(true);
}
public void distanceAlert(String message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle(getString(R.string.INVALID_DISTANCE));
alertDialog.setMessage(message);
alertDialog.setCancelable(true);
Drawable drawable = ContextCompat.getDrawable(getActivity(), R.mipmap.ic_warning_white_24dp);
drawable = DrawableCompat.wrap(drawable);
DrawableCompat.setTint(drawable, Color.RED);
alertDialog.setIcon(drawable);
alertDialog.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
alert = alertDialog.create();
alert.show();
}
private void dismiss() {
if (snackbar != null) {
snackbar.dismiss();
}
}
MapView.java
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.mapview, container, false);
BindView(savedInstanceState);
if (!CheckConnection.haveNetworkConnection(getActivity())) {
Toast.makeText(getActivity(), getString(R.string.network), Toast.LENGTH_LONG).show();
}
return view;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//serverKey = getResources().getString(R.string.google_android_map_api_key);
}
@Override
public void onDirectionSuccess(Direction direction, String rawBody) {
try {
if (direction.isOK()) {
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
myMap.addPolyline(DirectionConverter.createPolyline(getActivity(), directionPositionList, 5, Color.RED));
loader.setVisibility(View.GONE);
}
} catch (Exception e) {
loader.setVisibility(View.GONE);
}
myMap.addMarker(new MarkerOptions().position(new LatLng(origin.latitude, origin.longitude)).title("Pickup Location").snippet(pickup_location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
myMap.addMarker(new MarkerOptions().position(new LatLng(destination.latitude, destination.longitude)).title("Drop Location").snippet(drop_location).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin, 50));
TextView distance = (TextView) view.findViewById(R.id.distance);
distance.setText("");
}
@Override
public void onDirectionFailure(Throwable t) {
Log.d("direction fail", t.toString());
loader.setVisibility(View.GONE);
}
@Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
myMap.setMaxZoomPreference(80);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
requestDirection();
}
});
thread.start();
Log.d("max", myMap.getMaxZoomLevel() + "");
}
public void requestDirection() {
Snackbar.make(view, "Direction Requesting...", Snackbar.LENGTH_SHORT).show();
GoogleDirection.withServerKey(serverKey)
.from(origin)
.to(destination)
.transportMode(TransportMode.DRIVING)
.execute(this);
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onMapLoaded() {
//myMap.resetMinMaxZoomPreference();
}
public void BindView(Bundle savedInstanceState) {
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.track_ride));
mMapView = (com.google.android.gms.maps.MapView) view.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
loader = (TextView) view.findViewById(R.id.txt_loader);
loader.setVisibility(View.VISIBLE);
Bundle bundle = getArguments();
try {
if (bundle != null) {
pojo = (PendingRequestPojo) bundle.getSerializable("data");
pickup_location = pojo.getPikup_location();
drop_location = pojo.getDrop_locatoin();
try {
String[] latlong = pojo.getPikup_location().split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
String[] latlong1 = pojo.getDrop_locatoin().split(",");
double latitude1 = Double.parseDouble(latlong1[0]);
double longitude1 = Double.parseDouble(latlong1[1]);
origin = new LatLng(latitude, longitude);
destination = new LatLng(latitude1, longitude1);
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString() + " ", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
loader.setVisibility(View.GONE);
Toast.makeText(getActivity(), "location error", Toast.LENGTH_LONG).show();
}
askCompactPermissions(permissionAsk, new PermissionResult() {
@Override
public void permissionGranted() {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
@Override
public void permissionDenied() {
}
@Override
public void permissionForeverDenied() {
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Tracking/" + pojo.getRide_id());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Tracking tracking = dataSnapshot.getValue(Tracking.class);
if (marker == null) {
Log.e("Print",tracking.getStatus());
marker = myMap.addMarker(new MarkerOptions().position(new LatLng(tracking.getDriver_latitude(), tracking.getDriver_longitude())).title(getString(R.string.driver)).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
} else {
marker.setPosition(new LatLng(tracking.getDriver_latitude(), tracking.getDriver_longitude()));
}
marker.showInfoWindow();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@SuppressWarnings("MissingPermission")
@Override
public void onConnected(@Nullable Bundle bundle) {
android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
setCurrentLocation(currentLatitude, currentLongitude);
// Toast.makeText(getActivity(), "" + currentLatitude + " " + currentLongitude, Toast.LENGTH_LONG, Gravity.CENTER_VERTICAL);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), 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.d("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("location", currentLatitude + " " + currentLongitude);
setCurrentLocation(currentLatitude, currentLongitude);
}
private void setCurrentLocation(final Double currentLatitude, final Double currentLongitude) {
@SuppressWarnings("MissingPermission")
PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
@Override
public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
if(usermarker==null){
usermarker=myMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Your Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.taxi)).snippet(likelyPlaces.get(0).getPlace().getAddress().toString()));
}else {
usermarker.setPosition(new LatLng(currentLatitude, currentLongitude));
usermarker.setSnippet(likelyPlaces.get(0).getPlace().getAddress().toString());
}
likelyPlaces.release();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
getCurrentlOcation();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
public void getCurrentlOcation() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
// The next two lines tell the new client that “this” current class will handle connection stuff
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.addApi(Places.PLACE_DETECTION_API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
}
public void tunonGps() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
// **************************
builder.setAlwaysShow(true); // this is the key ingredient
// **************************