指南针:将图像旋转到特定位置

时间:2015-07-01 16:52:33

标签: android location latitude-longitude compass

我需要将图像箭头旋转到特定位置。这是我目前的代码:

    public void onSensorChanged(SensorEvent event) {
        float azimuth = event.values[0];
        Location currentLoc = getHelper().getCurrentLocation();
        if(currentLoc == null || cardinal == null || cardinal.getLocation() == null) {
            return;
        }

        azimuth = (float) Math.toDegrees(azimuth);
        GeomagneticField geoField = new GeomagneticField(
                (float) currentLoc.getLatitude(),
                (float) currentLoc.getLongitude(),
                (float) currentLoc.getAltitude(),
                System.currentTimeMillis());

        azimuth += geoField.getDeclination(); // converts magnetic north into true north
        float bearing = currentLoc.bearingTo(cardinal.getLocation()); // (it's already in degrees)
        float direction = azimuth - bearing;
        direction = -direction;
        if(compass != null) {
            compass.setDirection(direction);
        }
}

这是我的自定义imageview:

public void onDraw(Canvas canvas) { //
    int height = this.getHeight();  //
    int width = this.getWidth();

    canvas.rotate(direction, width / 2, height / 2); //
    super.onDraw(canvas); //
}

这是我正在使用的箭头图像: enter image description here

此代码根本不起作用。任何人都可以指出我在哪里做错了吗?

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。我正在为寻找相同解决方案的其他人发布答案:这是更新后的代码:

    float azimuth = event.values[0];
        Location currentLoc = getHelper().getCurrentLocation();
        if(currentLoc == null || cardinal == null || cardinal.getLocation() == null) {
            return;
        }

        try {
            GeomagneticField geoField = new GeomagneticField(
                    Double.valueOf(currentLoc.getLatitude()).floatValue(),
                    Double.valueOf(currentLoc.getLongitude()).floatValue(),
                    Double.valueOf(currentLoc.getAltitude()).floatValue(),
                    System.currentTimeMillis() );

            float myBearing = currentLoc.bearingTo(cardinal.getLocation());

            azimuth += geoField.getDeclination();
            azimuth = (myBearing - azimuth) * -1;
            azimuth = normalizeDegree(azimuth);
//            compass.updateValues(-azimuth);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(compass != null) {
            compass.setDirection(-azimuth);
        }
相关问题