Search code examples
flutterdartlocationcompassdirection

How to find direction with flutter compass?


Is there any way to find a specific direction with a Flutter compass. Does that compass indicate a specific long and lat coordinates?


Solution

  • This is the standard code for Qibla compasses I use in my apps to get the offset:

      double getOffsetFromNorth(double currentLatitude, double currentLongitude,
          double targetLatitude, double targetLongitude) {
        var la_rad = radians(currentLatitude);
        var lo_rad = radians(currentLongitude);
    
        var de_la = radians(targetLatitude);
        var de_lo = radians(targetLongitude);
    
        var toDegrees = degrees(atan(sin(de_lo - lo_rad) /
            ((cos(la_rad) * tan(de_la)) - (sin(la_rad) * cos(de_lo - lo_rad)))));
        if (la_rad > de_la) {
          if ((lo_rad > de_lo || lo_rad < radians(-180.0) + de_lo) &&
              toDegrees > 0.0 &&
              toDegrees <= 90.0) {
            toDegrees += 180.0;
          } else if (lo_rad <= de_lo &&
              lo_rad >= radians(-180.0) + de_lo &&
              toDegrees > -90.0 &&
              toDegrees < 0.0) {
            toDegrees += 180.0;
          }
        }
        if (la_rad < de_la) {
          if ((lo_rad > de_lo || lo_rad < radians(-180.0) + de_lo) &&
              toDegrees > 0.0 &&
              toDegrees < 90.0) {
            toDegrees += 180.0;
          }
          if (lo_rad <= de_lo &&
              lo_rad >= radians(-180.0) + de_lo &&
              toDegrees > -90.0 &&
              toDegrees <= 0.0) {
            toDegrees += 180.0;
          }
        }
        return toDegrees;
      }
    

    then you add the offset to the flutter_compass rotation to get the offset for each sensor update and apply the result to the special header.