为什么我的位置错误?

时间:2016-03-10 14:19:24

标签: java android gps location

我正在尝试制作指南针并希望打印出Textview中的当前位置。但是,当我这样做时,它给了我德黑兰(伊朗)的经纬度,这是不正确的。

public class Kompas extends AppCompatActivity implements AnimationListener,
        OnSharedPreferenceChangeListener, ConstantUtilInterface {
    private boolean faceUp = true;
    private boolean gpsLocationFound = true;
    private String location_line2 = "";
    public Location currentLocation = null;

    private double lastTargetAngle = 0;
    private double lastNorthAngle = 0;
    private double lastTargetAngleFromN = 0;

    // This animation is used to rotate north and target images
    private RotateAnimation animation;

    private ImageView compassImageView;
    private ImageView locationImageView;

    private final LocationCompassManager locationCompassManager = new LocationCompassManager(this);

    private boolean angleSignaled = false;
    private Timer timer = null;

    private SharedPreferences perfs;

    public boolean isRegistered = false;
    public boolean isGPSRegistered = false;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            if (message.what == ROTATE_IMAGES_MESSAGE) {
                Bundle bundle = message.getData();

                boolean isTargetChanged = bundle.getBoolean(IS_TARGET_CHANGED);
                boolean isCompassChanged = bundle
                        .getBoolean(IS_COMPASS_CHANGED);

                double targetNewAngle = 0;
                double compassNewAngle = 0;
                if (isTargetChanged)
                    targetNewAngle = (Double) bundle.get(TARGET_BUNDLE_DELTA_KEY);
                if (isCompassChanged) {
                    compassNewAngle = (Double) bundle
                            .get(COMPASS_BUNDLE_DELTA_KEY);
                }
                // This
                syncTargetAndNorthArrow(compassNewAngle, targetNewAngle,
                        isCompassChanged, isTargetChanged);
                angleSignaled = false;
            }
        }

    };

    public void setLocationText(String textToShow) {
        this.location_line2 = textToShow;
    }


    private TimerTask getTimerTask() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                if (angleSignaled && !ConcurrencyUtil.isAnyAnimationOnRun()) {

                    // numAnimationOnRun += 2;
                    Map<String, Double> newAnglesMap = locationCompassManager
                            .fetchDeltaAngles();
                    Double newNorthAngle = newAnglesMap
                            .get(LocationCompassManager.NORTH_CHANGED_MAP_KEY);
                    Double newTargetAngle = newAnglesMap
                            .get(LocationCompassManager.TARGET_CHANGED_MAP_KEY);

                    Message message = mHandler.obtainMessage();
                    message.what = ROTATE_IMAGES_MESSAGE;
                    Bundle b = new Bundle();
                    if (newNorthAngle == null) {
                        b.putBoolean(IS_COMPASS_CHANGED, false);
                    } else {
                        ConcurrencyUtil.incrementAnimation();
                        b.putBoolean(IS_COMPASS_CHANGED, true);

                        b.putDouble(COMPASS_BUNDLE_DELTA_KEY, newNorthAngle);
                    }
                    if (newTargetAngle == null) {
                        b.putBoolean(IS_TARGET_CHANGED, false);

                    } else {
                        ConcurrencyUtil.incrementAnimation();
                        b.putBoolean(IS_TARGET_CHANGED, true);
                        b.putDouble(TARGET_BUNDLE_DELTA_KEY, newTargetAngle);
                    }

                    message.setData(b);
                    mHandler.sendMessage(message);
                } else if (ConcurrencyUtil.getNumAimationsOnRun() < 0) {

                }
            }
        };
        return timerTask;
    }

     private void schedule() {

        if (timer == null) {
            timer = new Timer();
            this.timer.schedule(getTimerTask(), 0, 200);
        } else {
            timer.cancel();
            timer = new Timer();
            timer.schedule(getTimerTask(), 0, 200);
        }
    }

      private void cancelSchedule() {

        if (timer == null)
            return;
        // timer.cancel();
    }


    private void onInvalidateLocation(String message) {

    }

    private void requestForValidationOfLocation() {
        // TextView textView = (TextView)
        // findViewById(R.id.location_text_line1);
        TextView textView2 = (TextView) findViewById(R.id.location_text_line2);
        ImageView arrow = ((ImageView) findViewById(R.id.arrowImage));
        ImageView compass = ((ImageView) findViewById(R.id.compassImage));
        ImageView frame = ((ImageView) findViewById(R.id.frameImage));
        FrameLayout targetFrame = ((FrameLayout) findViewById(R.id.targetLayout));
        LinearLayout noLocationLayout = ((LinearLayout) findViewById(R.id.noLocationLayout));

        if (faceUp && (gpsLocationFound || currentLocation != null)) {
            textView2.setVisibility(View.VISIBLE);
            textView2.setText(location_line2);
            ((LinearLayout) findViewById(R.id.textLayout))
                    .setVisibility(View.VISIBLE);
            noLocationLayout.setVisibility(View.INVISIBLE);
            targetFrame.setVisibility(View.VISIBLE);
            arrow.setVisibility(View.VISIBLE);
            compass.setVisibility(View.VISIBLE);
            frame.setVisibility(View.VISIBLE);
        } else {
            if (!faceUp) {
                onScreenDown();
            } else if (!(gpsLocationFound || currentLocation != null)) {
                onGPSOn();
            }
        }
    }

    private void onGPSOn() {
        gpsLocationFound = false;
        onInvalidateLocation(getString(R.string.no_location_yet));
    }

    public void onScreenDown() {
        faceUp = false;
        onInvalidateLocation(getString(R.string.screen_down_text));
    }

    public void onScreenUp() {
        faceUp = true;
        requestForValidationOfLocation();
    }

    public void onNewLocationFromGPS(Location location) {
        gpsLocationFound = true;
        currentLocation = location;
        requestForValidationOfLocation();
    }

    private void onGPSOff(Location defaultLocation) {
        currentLocation = defaultLocation;
        gpsLocationFound = false;
        requestForValidationOfLocation();
    }

    private String getLocationForPrint(double latitude, double longitude) {
        int latDegree = (new Double(Math.floor(latitude))).intValue();
        int longDegree = (new Double(Math.floor(longitude))).intValue();
        String latEnd = getString(R.string.latitude_south);
        String longEnd = getString(R.string.longitude_west);
        if (latDegree > 0) {
            latEnd = getString(R.string.latitude_north);

        }
        if (longDegree > 0) {
            longEnd = getString(R.string.longitude_east);
        }
        double latSecond = (latitude - latDegree) * 100;
        double latMinDouble = (latSecond * 3d / 5d);
        int latMinute = new Double(Math.floor(latMinDouble)).intValue();

        double longSecond = (longitude - longDegree) * 100;
        double longMinDouble = (longSecond * 3d / 5d);
        int longMinute = new Double(Math.floor(longMinDouble)).intValue();
        return String.format(getString(R.string.geo_location_info), latDegree,
                latMinute, latEnd, longDegree, longMinute, longEnd);


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kompas);

        registerListeners();

        Context context = getApplicationContext();
        perfs = PreferenceManager.getDefaultSharedPreferences(context);
        perfs.registerOnSharedPreferenceChangeListener(this);
        String gpsPerfKey = getString(R.string.gps_pref_key);
        TextView text1 = (TextView) findViewById(R.id.location_text_line2);
        TextView text2 = (TextView) findViewById(R.id.noLocationText);
        getLocationName(currentLocation.getLatitude(), currentLocation.getLongitude());

        getSupportActionBar().setTitle("Qiblah");
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8b4513")));


        boolean isGPS = false;
        try {
            isGPS = Boolean.parseBoolean(perfs.getString(gpsPerfKey, "false"));
        } catch (ClassCastException e) {
            isGPS = perfs.getBoolean(gpsPerfKey, false);
        }
        if (!isGPS) {
            unregisterForGPS();
            useDefaultLocation(perfs,
                    getString(R.string.state_location_pref_key));
        } else {
            registerForGPS();
            onGPSOn();
        }
        this.locationImageView = (ImageView) findViewById(R.id.arrowImage);
        this.compassImageView = (ImageView) findViewById(R.id.compassImage);
    }

    private void unregisterListeners() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                  return;
        }
        ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                .removeUpdates(locationCompassManager);

        ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                .removeUpdates(locationCompassManager);
        SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor gsensor = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor msensor = mSensorManager
                .getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.unregisterListener(locationCompassManager, gsensor);
        mSensorManager.unregisterListener(locationCompassManager, msensor);
        cancelSchedule();

    }


    public void getLocationName(double lattitude, double longitude) {

    }

    private void registerForGPS() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE));
        String provider = locationManager.getBestProvider(criteria, true);

        if (provider != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME,
                    MIN_LOCATION_DISTANCE, locationCompassManager);
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, locationCompassManager);
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME,
                MIN_LOCATION_DISTANCE, locationCompassManager);
        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location == null) {
            location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if (location != null) {
            locationCompassManager.onLocationChanged(location);
        }

    }

    private void unregisterForGPS() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                     return;
        }
        ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                .removeUpdates(locationCompassManager);

    }

    private void registerListeners() {
        SharedPreferences perfs = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());
        if (perfs.getBoolean(getString(R.string.gps_pref_key), false)) {
            registerForGPS();
        } else {
            useDefaultLocation(perfs,
                    getString(R.string.state_location_pref_key));
        }
        SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor gsensor = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        Sensor msensor = mSensorManager
                .getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        mSensorManager.registerListener(locationCompassManager, gsensor,
                SensorManager.SENSOR_DELAY_GAME);
        mSensorManager.registerListener(locationCompassManager, msensor,
                SensorManager.SENSOR_DELAY_GAME);
        schedule();
        isRegistered = true;

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerListeners();
    }

    @Override
    protected void onPause() {
        super.onPause();
        ConcurrencyUtil.setToZero();
        ConcurrencyUtil.directionChangedLock.readLock();
        unregisterListeners();
    }

    public void syncTargetAndNorthArrow(double northNewAngle,
                                        double targetNewAngle, boolean northChanged, boolean targetChanged) {
        if (northChanged) {
            lastNorthAngle = rotateImageView(northNewAngle, lastNorthAngle,
                    compassImageView);

            if (targetChanged == false && targetNewAngle != 0) {
                lastTargetAngleFromN = targetNewAngle;
                lastTargetAngle = rotateImageView(targetNewAngle + northNewAngle,
                        lastTargetAngle, locationImageView);
            } else if (targetChanged == false && targetNewAngle == 0)

                lastTargetAngle = rotateImageView(lastTargetAngleFromN
                        + northNewAngle, lastTargetAngle, locationImageView);

        }
        if (targetChanged) {
            lastTargetAngleFromN = targetNewAngle;
            lastTargetAngle = rotateImageView(targetNewAngle + lastNorthAngle,
                    lastTargetAngle, locationImageView);

        }
    }

    private double rotateImageView(double newAngle, double fromDegree,
                                   ImageView imageView) {

        newAngle = newAngle % 360;
        double rotationDegree = fromDegree - newAngle;
        rotationDegree = rotationDegree % 360;
        long duration = new Double(Math.abs(rotationDegree) * 2000 / 360)
                .longValue();
        if (rotationDegree > 180)
            rotationDegree -= 360;
        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.targetLayout);
        float toDegree = new Double(newAngle % 360).floatValue();
        final int width = Math.abs(frameLayout.getRight()
                - frameLayout.getLeft());
        final int height = Math.abs(frameLayout.getBottom()
                - frameLayout.getTop());

        LinearLayout main = (LinearLayout) findViewById(R.id.mainLayout);
        float pivotX = width / 2f;
        float pivotY = height / 2f;
        animation = new RotateAnimation(new Double(fromDegree).floatValue(),
                toDegree, pivotX, pivotY);
        animation.setRepeatCount(0);
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());
        animation.setFillEnabled(true);
        animation.setFillAfter(true);
        animation.setAnimationListener(this);
        imageView.startAnimation(animation);
        return toDegree;

    }

    public void signalForAngleChange() {
        this.angleSignaled = true;
    }

    public void onAnimationEnd(Animation animation) {
        if (ConcurrencyUtil.getNumAimationsOnRun() <= 0) {

        } else {
            ConcurrencyUtil.decrementAnimation();
        }
        schedule();
    }

    public void onAnimationRepeat(Animation animation) {
    }

    public void onAnimationStart(Animation animation) {
        cancelSchedule();

    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        String gpsPerfKey = getString(R.string.gps_pref_key);
        String defaultLocationPerfKey = getString(R.string.state_location_pref_key);
        if (gpsPerfKey.equals(key)) {
            boolean isGPS = false;
            try {
                isGPS = Boolean.parseBoolean(sharedPreferences.getString(key,
                        "false"));
            } catch (ClassCastException e) {
                isGPS = sharedPreferences.getBoolean(key, false);
            }
            if (isGPS) {
                registerForGPS();
                currentLocation = null;
                onGPSOn();
            } else {
                useDefaultLocation(sharedPreferences, defaultLocationPerfKey);
                unregisterForGPS();

            }
        } else if (defaultLocationPerfKey.equals(key)) {
            sharedPreferences.edit().putBoolean(gpsPerfKey, false);
            sharedPreferences.edit().commit();
            unregisterForGPS();
            useDefaultLocation(sharedPreferences, key);
        }

    }


    private void useDefaultLocation(SharedPreferences perfs, String key) {
        int defLocationID = Integer.parseInt(perfs.getString(key, ""
                + LocationEnum.MENU_TEHRAN.getId()));
        LocationEnum locationEnum = LocationEnum.values()[defLocationID - 1];
        Location location = locationEnum.getLocation();
        locationCompassManager.onLocationChanged(location);
        onGPSOff(location);
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}

我发现的方式是我打印出城市名称和纬度/经度,他们给了我德黑兰。我已在Manifest中写入了正确的权限,并在我的设备上打开了GPS /位置

1 个答案:

答案 0 :(得分:0)

您希望实现所谓的DEG到DMS转换(十进制度到度数分钟,秒)。

你的公式似乎错了: 特别是longSecond * 3d / 5d); 有关正确的公式,请查看第一行: https://en.wikipedia.org/wiki/Geographic_coordinate_conversion