簡體   English   中英

為什么我得到 Lat Long 0.0?

[英]Why I am getting Lat Long 0.0?

點擊后默認數據保存默認保存 Static 數據保存發送靜態數據

我正在正確獲取當前位置,但是當將緯度和緯度存儲到我的 sqlite 數據庫中時,我的表中得到了經度和經度 0.0。 它顯示 lat 和 lang 0.0,其他值為 null。

public class MapActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
TextView add;
Button button;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
String getbuildingname,locality,subLocality,current_state,current_country,postal_code;
double longitude,latitude;
private GoogleMap mMap;
DatabaseHelper databaseHelper;
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    databaseHelper = new DatabaseHelper(this);
    button = findViewById(R.id.button);
    add = (TextView)findViewById(R.id.current_location);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager()
                    .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    add_location();

}
// Map ready method
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setZoomGesturesEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);
    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(MapActivity.this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    }
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }
 //Showing Current Location Marker on Map
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    assert provider != null;
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String> providerList = locationManager.getAllProviders();
    if (null != locations && providerList.size() > 0) {
        longitude = locations.getLongitude();
        latitude = locations.getLatitude();

        // Geo Coder
        Geocoder geocoder = new Geocoder(getApplicationContext(),
                Locale.getDefault());
        try {
            List<Address> listAddresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            if (null != listAddresses && listAddresses.size() > 0) {
                getbuildingname = listAddresses.get(0).getPremises(); 
                locality = listAddresses.get(0).getLocality();
                subLocality = listAddresses.get(0).getSubLocality();//  
                current_state = listAddresses.get(0).getAdminArea(); // 
                current_country = listAddresses.get(0).getCountryName(); // India
                postal_code = listAddresses.get(0).getPostalCode(); // 
                markerOptions.title(""+getbuildingname+","+locality+"," + subLocality + "," +
                        current_state + "," + current_country + "," + postal_code);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                this);
    }
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "permission denied",
                        Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}

private void add_location(){
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
            Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
        }
    });
}

 //Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

// Database Helper 
boolean insert_location(String lat , String lang , String state , String country, String pin){

    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(Location_Table_Column2,lat);
    values.put(Location_Table_Column3,lang);
    values.put(Location_Table_Column5,state);
    values.put(Location_Table_Column6,country);
    values.put(Location_Table_Column7,pin);
    long result =database.insert(Table_Name_Loaction,null,values);
    return result != -1;
}

很多時候,當我點擊 pin 時,地址標題會消失。 表創建成功,lat 和 lang 保存為 0.0,其他值為 null。

愚蠢的錯誤

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String lat = String.valueOf(latitude);
            String lng = String.valueOf(longitude);
            databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
            Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
        }

它會在檢測到它不為空時捕獲該位置和其他位置

Geocoder geocoder;
        List<Address> listAddresses;
        geocoder = new Geocoder(this, Locale.getDefault());

        try {
            listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
            if(!listAddresses.get(0).getLocality(0).equals("") || !listAddresses.get(0).getAdminArea(0).equals("") || !listAddresses.get(0).getCountryName(0).equals("")) {
                locality = listAddresses.get(0).getLocality(0);
                current_state = listAddresses.get(0).getAdminArea(0);
                current_country = listAddresses.get(0).getCountryName(0);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

並將其添加到您的 onClick 上,它將驗證您的輸入

if(lat.equal("") ||lng.equal("") ||locality.equal("") ||current_state.equal("") ||current_country.equal("") ){

                    Toast.makeText(MapsActivity.this, "Somethings Empty", Toast.LENGTH_SHORT).show();

                }else{
                    databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
                    Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM