import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MapsFragment extends Fragment implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
private static final String TAG = "MapsFragment";
private static final int PERMISSIONS_REQUEST_LOCATION = 100;
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
};
}
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng currentLatLng = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
}
}
private void drawRoute(LatLng origin, LatLng destination) {
String apiKey = "AIzaSyB7Dxn7v2_8vyFin-mIq7Fms6qZy72Azfo";
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=" + origin.latitude + "," + origin.longitude + "&destination=" + destination.latitude + "," + destination.longitude + "&key=" + apiKey;
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray routes = response.getJSONArray("routes");
if (routes.length() > 0) {
JSONArray legs = routes.getJSONObject(0).getJSONArray("legs");
if (legs.length() > 0) {
JSONArray steps = legs.getJSONObject(0).getJSONArray("steps");
if (steps.length() > 0) {
PolylineOptions polylineOptions = new PolylineOptions();
for (int i = 0; i < steps.length(); i++) {
JSONObject step = steps.getJSONObject(i);
if (step.has("start_location")) {
JSONObject startLocation = step.getJSONObject("start_location");
LatLng startLatLng = new LatLng(startLocation.getDouble("lat"), startLocation.getDouble("lng"));
polylineOptions.add(startLatLng);
}
if (i == steps.length() - 1 && step.has("end_location")) {
JSONObject endLocation = step.getJSONObject("end_location");
LatLng endLatLng = new LatLng(endLocation.getDouble("lat"), endLocation.getDouble("lng"));
polylineOptions.add(endLatLng);
}
}
polylineOptions.color(Color.BLUE);
polylineOptions.width(10);
mMap.clear(); // clear existing polylines
mMap.addPolyline(polylineOptions);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error getting directions", error);
}
});
queue.add(request);
}
// Call this method wherever you want to draw the route
@SuppressLint("MissingPermission")
private void showRoute() {
LatLng originLatLng = new LatLng(9.2879, 4.1489);
@SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocation != null) {
LatLng currentLatLng = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
drawRoute(currentLatLng, originLatLng);
} else {
// Last known location not available, request location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
我本来希望在我当前位置的两点和另一个点之间绘制一条路线,但谷歌地图根本没有加载。我已经获得了谷歌地图 API 并启用了方向 API 和谷歌地图 API,但我尚未启用计费,这可能是原因 代码运行得很好,但没有做它应该做的事情
您是否已在清单中添加了地图 API 密钥? 类似这样的东西:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value=".................................">
</meta-data>