对不起,如果我的问题看起来很愚蠢,但是我是开发人员和android的新手。我写了一个代码段,我想在其中显示Google Map并获取当前位置或用户选择的位置。但是用Geocoder显示的地址不是很准确,特别是在十字路口。你能告诉我如何解决这个问题吗?关于我的代码质量的任何观察也将不胜感激。
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps"></activity>
<activity android:name=".ReturnVehicleActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MapsActivity.java
package m.example.mapapp2;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.PlaceDetectionClient;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
//Our Map
private GoogleMap mMap;
private static final int REQUEST_LOCATION_PERMISSION = 1;
//To store longitude and latitude from map
// private Location mylocation;
private double longitude = 0;
private double latitude = 0;
//public double currentLongLocation = 0;
//public double currentLatLocation = 0;
private String address;
private Location mylocation;
//Buttons
private ImageButton buttonSave;
private ImageButton buttonCurrent;
private ImageButton buttonView;
//Google ApiClient
private GoogleApiClient googleApiClient;
private FusedLocationProviderClient mFusedLocationClient;
private PlaceDetectionClient mPlaceDetectionClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
//Initializing googleapi client
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//Initializing views and adding onclick listeners
buttonSave = (ImageButton) findViewById(R.id.buttonSave);
buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
buttonView = (ImageButton) findViewById(R.id.buttonView);
buttonSave.setOnClickListener(this);
buttonCurrent.setOnClickListener(this);
buttonView.setOnClickListener(this);
// Initialize the FusedLocationClient.
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(
this);
// Initialize the PlaceDetectionClient.
mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
}
/**
* 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) {
//Setting the level of zoom
float zoom = 10;
//Initializing our map
mMap = googleMap;
//Creating a random coordinate
LatLng latLng = new LatLng(43.000000, 23.000000);
//Adding marker to that coordinate
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
//Setting onMarkerDragListener to track the marker drag
mMap.setOnMarkerDragListener(this);
//Adding a long click listener to the map
mMap.setOnMapLongClickListener(this);
}
@Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast messageToast = Toast.makeText(MapsActivity.this, "Connexion Failed",
Toast.LENGTH_SHORT);
}
@Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
mMap.clear();
String snippet = String.format(Locale.getDefault(),
"Lat: %1$.5f, Long: %2$.5f",
latLng.latitude,
latLng.longitude);
//Adding a new marker to the current pressed position we are also making the draggable true
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true)
.snippet(snippet));
latitude = latLng.latitude;
longitude = latLng.longitude;
address = getAddress(MapsActivity.this, latitude, longitude);
Toast addressMessage = Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT);
addressMessage.show();
}
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
@Override
public void onClick(View v) {
if (v == buttonCurrent) {
getCurrentLocation();
moveMap();
} else {
if (v == buttonSave) {
Intent returnVehicleIntent = new Intent(MapsActivity.this, ReturnVehicleActivity.class);
startActivity(returnVehicleIntent);
}
}
}
@Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
@Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
private void getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
mMap.clear();
mFusedLocationClient.getLastLocation().addOnSuccessListener(
new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mylocation = location;
longitude = location.getLongitude();
latitude = location.getLatitude();
address = getAddress(MapsActivity.this, latitude, longitude);
Toast addressMesage = Toast.makeText(MapsActivity.this, address, Toast.LENGTH_SHORT);
addressMesage.show();
moveMap();
} else {
Toast testsMesagge = Toast.makeText(MapsActivity.this, "No location available", Toast.LENGTH_SHORT);
testsMesagge.show();
}
}
});
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION:
// If the permission is granted, get the location,
// otherwise, show a Toast
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
Toast.makeText(this,
R.string.location_permission_denied,
Toast.LENGTH_SHORT).show();
}
break;
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", " + longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Creating the snippet that will be displayed in marker
String snippet = String.format(Locale.getDefault(),
"Lat: %1$.5f, Long: %2$.5f",
latLng.latitude,
latLng.longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.title("Current Location") //Adding a title
.snippet(snippet)); //Adding a snippet
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
public String getAddress(Context context, double lat, double lng) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
add = add + "," + obj.getAdminArea();
add = add + "," + obj.getCountryName();
return add;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
}
答案 0 :(得分:0)
对于准确性问题,它完全取决于您所获得的&variable
。
因此,您可以检查正在使用LatLng
的{{1}}的准确性,如果准确性很差,请再次请求LatLng
。
为确保代码一致性,您需要检查Google Play服务是否最新,可用,以及目标设备是否支持。
我希望这能回答您的问题,如果您有任何需要,我可以为您提供帮助。