我目前正在学校项目中进行地图相关的应用程序。 我以某种方式取得了当前位置并在搜索到的地址上做了标记。 但是我不明白如何找到从当前位置到标记的方向。我知道我必须使用Direction api,但我迷路了,请帮助我
这是我的代码
public class MapsActivity2 extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private GoogleMap mMap;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 1234;
private static final int PLACE_PICKER_REQUEST = 1;
private static final String TAG = "MapActivity2";
private static final float DEFAULT_ZOOM = 10;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(new LatLng(-40,-168), new LatLng(71, 136));
private Boolean mLocationPermissionGranted = false;
private FusedLocationProviderClient mFusedLocationClient;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private GeoDataClient mGeoDataClient;
private PlaceInfo mPlace;
private Marker mMarker;
private AutoCompleteTextView mSearchText;
private ImageView mGps, mInfo, mPlacePicker;
private GeoApiContext mGeoApiContext = null;
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
// 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);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
mInfo = (ImageView) findViewById(R.id.place_info);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
getLocationPermission();
if (mGeoApiContext == null){
mGeoApiContext = new GeoApiContext.Builder()
.apiKey(getString(R.string.google_maps_key)).build();
}
}
private void init(){
Log.d(TAG, "init: initialising enter key");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener);
mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutocompleteAdapter);
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEARCH
|| i == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {
geoLocate();
}
return false;
}
});
mGps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getDeviceLocation();
}
});
mInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onclick: clicked place info");
try{
if (mMarker.isInfoWindowShown()){
mMarker.hideInfoWindow();
}else {
Log.d(TAG, "onclick: place info" + mPlace.toString());
mMarker.showInfoWindow();
}
}catch (NullPointerException e){
Log.e(TAG, "onClick: NullPointerException" + e.getMessage());
}
}
});
mPlacePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(MapsActivity2.this), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
Log.e(TAG, "onClick:GooglePlayServicesRepairableException: "+ e.getMessage());
} catch (GooglePlayServicesNotAvailableException e) {
Log.e(TAG, "onClick:GooglePlayServicesNotAvailableException: "+ e.getMessage());
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST){
if (resultCode == RESULT_OK){
Place place = PlacePicker.getPlace(this, data);
PendingResult<PlaceBuffer> placeResut = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, place.getId());
placeResut.setResultCallback(mUpdatePlaceDetailsCallback);
}
}
}
private void geoLocate(){
Log.d(TAG, "geolocate: geolocating");
String searchingString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapsActivity2.this);
List<Address> list = new ArrayList<>();
try {
list = geocoder.getFromLocationName(searchingString, 1);
}catch (IOException e){
Log.e(TAG, "geolocate: IOException" + e.getMessage());
}
if (list.size() > 0){
Address address = list.get(0);
//Toast.makeText(this, address.toString(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "geolocate: found location 123123 "+ address.toString());
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()),DEFAULT_ZOOM, address.getAddressLine(0));
}
}
/**
* 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.
*/
private void getDeviceLocation(){
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
try{
if (mLocationPermissionGranted){
final Task Location = mFusedLocationClient.getLastLocation();
Location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
Log.d(TAG, "onComplete: Found Location");
android.location.Location currentLocation = (android.location.Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()), DEFAULT_ZOOM , "my location");
}else {
Log.d(TAG, "onComplete: Current Location");
//Toast.makeText(MapsActivity2.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: Security exception: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom, PlaceInfo placeInfo){
Log.d(TAG, "moveCamera: moving to : " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
mMap.clear();
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity2.this));
if (placeInfo != null){
try{
String snippet = "Address: " + placeInfo.getAddress() + "\n" +
"Phone Number: " + placeInfo.getPhoneNumber() + "\n" +
"Website: " + placeInfo.getWebsiteUri() + "\n" +
"Rating: " + placeInfo.getRating() + "\n";
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title(placeInfo.getName())
.snippet(snippet);
mMarker = mMap.addMarker(options);
}catch (NullPointerException e){
Log.e(TAG, "NullPointerException: " + e.getMessage());
}
}else {
mMap.addMarker(new MarkerOptions().position(latLng));
}
}
private void moveCamera(LatLng latLng, float zoom, String title){
Log.d(TAG, "moveCamera: moving to : " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if (!title.equals("my location")){
MarkerOptions options = new MarkerOptions().position(latLng).title(title);
mMap.addMarker(options);
}
}
private void getLocationPermission(){
String [] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted = true;
}else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSIONS_REQUEST_CODE);
}
}
else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSIONS_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mLocationPermissionGranted = false;
switch (requestCode){
case LOCATION_PERMISSIONS_REQUEST_CODE:{
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
return;
}
}
mLocationPermissionGranted = true;
}
}
}
}
private AdapterView.OnItemClickListener mAutocompleteClickListener= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final AutocompletePrediction item = mPlaceAutocompleteAdapter.getItem(i);
final String placeID = item.getPlaceId();
PendingResult<PlaceBuffer> placeResut = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeID);
placeResut.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer places) {
if(!places.getStatus().isSuccess()){
Log.d(TAG, "onResult: place query not successful: "+ places.getStatus().toString());
places.release();//prevent memory leak
return;
}
final Place place = places.get(0);
try {
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
mPlace.setAddress(place.getAddress().toString());
//mPlace.setAttribution(place.getAttributions().toString());
mPlace.setId(place.getId());
mPlace.setLatlng(place.getLatLng());
mPlace.setRating(place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "OnResult: place" + mPlace.toString());
}catch (NullPointerException e) {
Log.e(TAG, "onResult: NullPointerException" + e.getMessage());
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude, place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace);
places.release();
}
};
}