当我使用以下代码并获取我当前的位置时,我的位置非常接近我的位置但不是我的位置?这是为什么? 提前谢谢![这就是红色标记是我得到的位置,蓝点是我的实际位置谷歌地图] [1]
package com.example.routepilot;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.example.routepilot.GoTo.GPSTracker;
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.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlayOptions;
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.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class Map extends FragmentActivity {
String stringLatitude;
String stringLongitude;
String country;
String city;
String postalCode;
String addressLine;
private GoogleMap mMap;
private LocationManager locationManager;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
stringLatitude = String.valueOf(gpsTracker.latitude);
stringLongitude = String.valueOf(gpsTracker.longitude);
country = gpsTracker.getCountryName(this);
city = gpsTracker.getLocality(this);
postalCode = gpsTracker.getPostalCode(this);
addressLine = gpsTracker.getAddressLine(this);
} else {
System.out
.println("################################### cannot get location");
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
Double lat = Double.parseDouble(stringLatitude);
Double lon = Double.parseDouble(stringLongitude);
System.out.println("##################### doubel lat -" + lat);
/*
* String lati= bundle.getString("latitude"); String longi=
* bundle.getString("longitude"); String country=
* bundle.getString("country"); String city= bundle.getString("city");
* String postalcode= bundle.getString("postalcode"); String address=
* bundle.getString("address");
*/
LatLng mylocation = new LatLng(lat, lon);
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(mylocation).title(country + " " + city)
.snippet(postalCode + " " + addressLine)
// .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow))
.draggable(false));
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Context context = getApplicationContext();
CharSequence text = "Directing you to the web site";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent i3 = new Intent(Map.this, Webpage.class);
startActivity(i3);
}
});
/*
* // Instantiates a new Polyline object and adds points to define a
* rectangle PolylineOptions rectOptions = new PolylineOptions()
* .add(new LatLng(37.35, -122.0)) .add(new LatLng(37.45, -122.0)) //
* North of the previous point, but at the same longitude .add(new
* LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
* .add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the
* south .add(new LatLng(37.35, -122.0)); // Closes the polyline.
*
* // Get back the mutable Polyline Polyline polyline =
* mMap.addPolyline(rectOptions);
*/
PolylineOptions line = new PolylineOptions()
.add(new LatLng(6.927078600000000000, 79.861243000000060000),
new LatLng(6.934078600000000000, 79.561243000000060000))
.width(5).color(Color.RED);
mMap.addPolyline(line);
LatLng NEWARK = new LatLng(6.934078600000000000, 79.561243000000060000);
GroundOverlayOptions newarkMap = new GroundOverlayOptions().image(
BitmapDescriptorFactory.fromResource(R.drawable.arrow))
.position(NEWARK, 8600f, 6500f);
mMap.addGroundOverlay(newarkMap);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon),
14.0f));
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
mMap.getUiSettings().setRotateGesturesEnabled(true);
}
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
android.location.Location location;
double latitude;
double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1
// minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public android.location.Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener Calling this function will stop using GPS in
* your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("title");
// Setting Dialog Message
alertDialog.setMessage("message");
// On Pressing Setting button
// On pressing cancel button
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
*
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(
latitude, longitude, 1);
return addresses;
} catch (IOException e) {
// e.printStackTrace();
Log.e("Error : Geocoder",
"Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
*
* @return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
*
* @return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
/**
* Try to get Postal Code
*
* @return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
*
* @return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(android.location.Location arg0) {
// TODO Auto-generated method stub
}
}
protected void onPause() {
super.onPause();
System.gc();
}
}
答案 0 :(得分:0)
如果您想要当前的位置,那么您可以使用此代码..
将此代码放在您要检索位置的位置
if (gpstracker.canGetLocation()) {
double lattitude = gpstracker.getLatitude();
double longitude = gpstracker.getLongitude();
} else {
Toast.makeText(getApplicationContext(), "Please turn on Your GPS.",
Toast.LENGTH_LONG).show();
}
//创建一个名为GPSTracker的类,并添加以下代码
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; //10 meters
private static final long MIN_TIME_BW_UPDATES=1000*60*1; //1 minute
private LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext=context;
getLocation();
}
public Location getLocation()
{
locationManager=(LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
}
else
{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if(locationManager!=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled)
{
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
}
if(locationManager != null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
return location;
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location != null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location != null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingAlert()
{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled .Do you want to go to settings menu ?");
alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(i);
}
});
alertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
//如果有任何其他查询,请告诉我
答案 1 :(得分:0)
原因是你从两个不同的来源获得Location
。
要解决此问题,请从LocationManager
(80%的代码)中移除与获取位置相关的所有代码,并将其替换为简单的调用:
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location currentLocation) {
// ...
}
}